C#中的if条件超出范围索引

时间:2019-02-27 13:15:51

标签: c# for-loop exception

我有一个句子,我想检查重复字母,以便在它们之间添加'x'作为分隔符,但是我调试并不断在这里得到异常:

for (int i = 0; i < res.Length; i++)
{
    t += res[i];

    if (res[i] == res[i + 1]) //Index out of range exception here
    {
        t += 'x';
    }
}

这里出了什么问题?

3 个答案:

答案 0 :(得分:1)

不当行为的原因在 <table datatable class="display table "> <thead> <tr> <th class="text-left" style="width: 300px!important;">name</th> </tr> </thead> <tbody> <tr> <td class="text-left" style="width: 300px!important;">jhon mathew</td> </tr> </tbody> </table> 中:

if

if (res[i] == res[i + 1]) i == res.Length - 1循环最后一次迭代)时,您拥有

for

if (res[res.Length - 1] == res[res.Length]) 抛出res[res.Length],因为有效范围是OutOfRangeException(请注意[0..res.Length - 1])。

您的代码已更正:

- 1

通常,我们会在正则表达式的帮助下与 for (int i = 0; i < res.Length; i++) { Nplaintext += res[i]; // we don't want to check (and insert 'x') for the last symbol if (i < res.Length - 1 && res[i] == res[i + 1]) { Nplaintext += 'x'; } } 合作(让.Net为您string循环):

string

结果:

  using System.Text.RegularExpressions;

  ...

  string source = "ABBBACCADBCAADA";

  // Any symbol followed by itself should be replaced with the symbol and 'x'
  string result = Regex.Replace(source, @"(.)(?=\1)", "$1x");

  Console.Write(result);

答案 1 :(得分:-1)

i + 1我们导致了此情况。

在上一次迭代中,i + 1指向不在该数组内部的位置。

更好地更改for循环中的条件,如下所示:

for (int i = 0; i < res.Length - 1; i++)
{
    t += res[i];

    if (res[i] == res[i + 1]) //Index out of range exception here
    {
        t += 'x';
    }
}

t += res[res.Length -1 ];

希望这会有所帮助。

答案 2 :(得分:-1)

确定您会遇到此异常。在i = res.Length -1(恰好是最后一个位置)的情况下,您要求使用i +1的res [Length],但是由于以0开头,所以您要的元素不存在。 尝试类似

if(i+i < res.Length)

在请求该元素之前 甚至最好从i = 1开始计数并使用

if (res[i] == res[i - 1]) 
        {
            Nplaintext += 'q';
        }