-1

I have a sentence, and I want to check for duplication letters in order to add a 'x' as a separator between them, however I debugged and kept getting an exception in here:

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';
    }
}

what goes wrong in here?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

3 Answers3

2

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Thank you. Finally, someone with a brain. Too many answers suggesting to change the for to `Length - 1`, completely unaware that nothing will happen with the last element of the array. – ThePerplexedOne Feb 27 '19 at 13:38
-1

i+1 us causing this.

in the last iteration, i+1 refers to a location which is not inside that array.

Better change the condition in for loop as below:

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 ];

Hope this helps.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
-1

Sure you get this exception. In the case i=res.Length -1 (what is exactly the last position) you ask for res[Length] with the i +1 but because of starting with 0 the element you are asking for does not exist. try something like

if(i+i < res.Length)

before you ask for that element or even better start counting with i=1 and use

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