【问题标题】:Argument OutofRange Exception was unhandled参数超出范围异常未处理
【发布时间】:2014-03-21 08:32:49
【问题描述】:

我的代码翻转了一个单词,它可以工作但显示此错误:

参数超出范围异常未处理

strFlippedWord = strUserWord.Sub... 行显示错误

string strUserWord;
string strFlippedWord;
int intWordLength;

System.Console.WriteLine("Please enter a word to flip: ");
strUserWord = System.Console.ReadLine();
intWordLength = strUserWord.Length;
while (intWordLength != -1)
{

    strFlippedWord = strUserWord.Substring(intWordLength - 1, 1); 
    System.Console.Write(strFlippedWord);
    intWordLength -= 1;
}

System.Console.ReadKey();

【问题讨论】:

  • 您是否要反转字符串,即“abc”->“cba”?

标签: c# string exception


【解决方案1】:

您的循环运行时间过长。

while (intWordLength > 0)

此外,您可以完全消除循环并使用一些 LINQ:

Console.WriteLine(strUserWord.Reverse().ToArray());

【讨论】:

  • 非常感谢。在我修复循环条件后它工作得很好。也感谢所有其他答案..:D
【解决方案2】:

intWordLength 为0 时,您将-1 作为第一个参数传递给String.Substring,这是一个无效参数。将您的 while 条件更改为 while( intWordLength > 0 )

【讨论】:

  • 字长为零时我错过了。
【解决方案3】:

这样的事情可能会奏效:

while (intWordLength != -1)
{
    if (intWordLength == 0)
    {
        break;
    }
    strFlippedWord = strUserWord.Substring(intWordLength - 1, 1);
    System.Console.Write(strFlippedWord);
    intWordLength -= 1;
 }

【讨论】:

    【解决方案4】:

    当 intWordLength 为 0 时,Substring 会抛出你看到的异常。

    http://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx

    在这种情况下,您传递的是 -1,这是不合法的。

    【讨论】:

      【解决方案5】:

      您从字符串中的最后一个字符开始并向前移动 1 个元素

      试试:

      strFlippedWord = strUserWord.Substring(intWordLength - 1, 0);
      

      如果你想反转字符串

      strFlippedWord = new string(strUserWord.Reverse().ToArray());
      

      编辑

      正如 babak 所说的 intwordlength:

      while 语句可以是

      while(!(intwordlength < 1) )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-19
        • 2014-07-23
        • 1970-01-01
        相关资源
        最近更新 更多