0

Possible Duplicate:
How do I count the number of occurrences of a char in a String?

I am looking to count the occurrences of a specific character, for example "i" that occurs in the input.

Example, from standard input: Lorem ipsum dolor sit amet, consectetur adipiscing elit.

This returns 6, because there are 6 occurrences of the letter "i" (case matters).

This could be accomplished with a loop stepping through the string with charAt(i).

Is there a more elegant way to accomplish this?

Community
  • 1
  • 1
Bobby S
  • 4,006
  • 9
  • 42
  • 61

2 Answers2

2

This is basically the same as stepping through a string, but you could create a method like so:

private int substrCount(string findStr, string str)
{
    lastIndex = 0;
    count = 0;
    while(lastIndex != -1){
        lastIndex = str.indexOf(findStr, lastIndex);

        if(lastIndex != -1){
            count++;
        }
    }
}
Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
ashurexm
  • 6,209
  • 3
  • 45
  • 69
  • I think this is more neat: public int countCharOccurrence(String string, char countChar){ int count = 0; for(int i =0; i – Ben Nov 19 '12 at 15:42
0

Bet you could loop over the results of String.indexOf(), specifically the two input form, where you can tell it to start looking at the location of the last match.

zigdon
  • 14,573
  • 6
  • 35
  • 54