The cause of misbehavior is in the if
:
if (res[i] == res[i + 1])
when i == res.Length - 1
(for
loop last iteration) you have
if (res[res.Length - 1] == res[res.Length])
and res[res.Length]
throws OutOfRangeException
since valid range is [0..res.Length - 1]
(please, note - 1
).
Your code corrected:
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';
}
}
Often we work with string
with a help of regular expressions (let .Net loop over the 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);
Outcome:
ABxBxBACxCADBCAxADA