'Counting character occurrences in a string - Java

I'm having trouble writing a method that takes a string and counts the number of times the first character (or really any character) appears. The code I've written is below, but for some reason keeps returning half the correct count when I run it. Any help would be appreciated, thanks.

public static void countOccurrences(String string1) {
    int counter = 0;
    char toCheck = string1.charAt(0);
    char compareChar;
    for (int i = 0; i < string1.length(); i++) {
        compareChar = string1.charAt(i);
        if (toCheck == compareChar) {
            counter++;
        }
        i++;
    }
    System.out.println(toCheck + " appears " + counter + " times in string1.");
}


Solution 1:[1]

You're incrementing i twice in each iteration, so you are skipping half the characters:

for (int i = 0; i < string1.length(); i++) { // i is incremented here

  compareChar = string1.charAt(i);
  if (toCheck == compareChar){
      counter++ ;
  }
  i++ ; // i is incremented again here - remove this line

}

Solution 2:[2]

i++ in for loop is incrementing the i value by 1, no need to increment inside th eloop

check Working of For loop here

  public static void countOccurrences(String string1) {

  int counter = 0;

  char toCheck = string1.charAt(0);

  char compareChar;

  for (int i = 0; i < string1.length(); i++) { 

      compareChar = string1.charAt(i);
      if (toCheck == compareChar){
          counter++ ;
      }
  }
  System.out.println(toCheck + " appears " + counter + " times in string1.");
}

Solution 3:[3]

Your immediate problem is that i++; happens twice per iteration.

An alternative approach is to use

s.length() - s.replace("x", "").length()

which gives you the number of times "x" appears in s. Arguably it's not the most efficient way, but it's clear.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eran
Solution 2 rhitz
Solution 3