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);
4
  • is it possible to include anyone failure story from I'm using different method Commented Dec 20, 2016 at 5:11
  • Possible duplicate of Count occurrence of a character in a string Commented Dec 20, 2016 at 5:11
  • Regex.Matches(input , pattern).Count where pattern is "ra" Commented Dec 20, 2016 at 5:13
  • @M.kazemAkhgary Ok, sorry, comment unwarranted. Commented Dec 20, 2016 at 10:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.