我有一个句子,我想检查重复字母以添加'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';
}
}
这里出了什么问题?
不当行为的原因在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';
}
}
通常,我们在正则表达式的帮助下与string
合作(让.NET循环 string
for You):
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
i 1我们引起了这一点。
在上次迭代中,i 1是指不在该数组中的位置。
最好更改以下循环中的条件:
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 ];
希望这会有所帮助。
确保您获得此异常。在情况下,i = res.length -1(到底是最后一个位置),您要求使用i 1进行res [长度],但由于从0开始,您要要求的元素就不存在。尝试
之类的东西if(i+i < res.Length)
在您要求该元素之前甚至最好以i = 1开始计数并使用
if (res[i] == res[i - 1])
{
Nplaintext += 'q';
}