C# if条件下的超出范围索引
我有一个句子,我想检查重复的字母,以便在它们之间添加一个C# if条件下的超出范围索引,c#,for-loop,exception,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'; } } for(int i=0;i
'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';
}
}
for(int i=0;i
这里出了什么问题 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 ];
for(int i=0;i
希望这有帮助。请确保您收到此异常。在i=res.Length-1的情况下(确切地说是最后一个位置),您要求i+1的res[Length],但由于从0开始,您要求的元素不存在。 试试像这样的东西
if(i+i < res.Length)
不当行为的原因在于
如果:
if (res[i] == res[i + 1])
当i==res.Length-1
(用于循环上一次迭代)时
if (res[res.Length - 1] == res[res.Length])
和res[res.Length]
抛出超出范围异常
,因为有效范围是[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';
}
}
结果:
ABxBxBACxCADBCAxADA
当i==res.Length-1
你有res[i+1]
被抛出exception.worked时,谢谢你没有正确的答案,但祝你好运。看起来最后一个字符不会被添加。@theerplexedone-我同意最后一个字符不会被添加,我会在这里更新完整的代码,但问题主要是关于索引外的例外,我相信这回答了这个问题。但是,不是吗?因为你产生了另一个问题。如果您更改for,t+=res[i]代码>对于最后一个元素将永远不会出现。谢谢。最后,一个有头脑的人。太多的答案建议将for更改为长度-1
,完全不知道数组的最后一个元素不会发生任何变化。
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);
ABxBxBACxCADBCAxADA