0

I have a string like a;sfjdksldrkdjlfdrarakdfkjra. I want to count how many times "ra" repeats in string above. I tried using different method but I failed.

string str = "rajdlkfja;ra;jdfsraralj;fra";
int count = 0;
char[] ch = str.ToCharArray();
for(int i = 0; i <= ch.Length; i++)
{
    if(ch[i] == 'r' && ch[i + 1] == 'a')
    {
        count++;
    }
}

Console.WriteLine(count);
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141

1 Answers1

3

The problem is that you have an IndexOutOfRangeException: bear in mind that arrays in C# are zero based which means that an array with n elements has indicees from 0 to n - 1 (when we humans count, we naturally start at one so 5 pears are 1, 2, 3, 4 and 5 pears, but in c# arrays we count them as pears at 0, at 1, at 2, at 3 and at 4).

So in general when you want to loop through an array, the rule of the thumb is: for (int i = 0; i < array.Length; i++) //< instead of <=.

Now, does that solve your problem? No, you still have an IndexOutOfRangeException. Why? The problem is that when i reaches the last valid value Length - 1 you are searching for a at ch[ch.Length - 1 + 1] which is ch[ch.Length] which we now know is wrong.

But wait a minute! Why are we searching for a two character pattern starting in the last character of a string? You can't possibly find a match at that position because there is no string left to match the second character in the pattern! We shouldn't be looking there at all! Ok then, only loop up to the before last character of the string: for (int i = 0; i < ch.Length - 1; i++).

And now your done, things should work just fine.

InBetween
  • 32,319
  • 3
  • 50
  • 90