Java Data Type How to - Get How many times the first character appears in a string








Question

We would like to know how to get How many times the first character appears in a string.

Answer

public class Main {
  public static void main(String[] args) {
    int count = 1;
    String userInput = "this is a test";
    char ch = userInput.charAt(0);
    for (int i = 1; i < userInput.length(); i++) {
      if (userInput.charAt(i) == ch)
        count++;/* w w  w  .j  av  a2s .  co m*/
    }
    System.out.println(count);

  }

}