Count Character occurrences in Java String

Want to learn how to count character occurrences in Java String?

Below is the program that uses a Map to store chars as keys and the number of occurrences as values.

class Test {

  public static void main(String[] args) {
    String str = "moiujjmhrqdoasdsooqavvae";

    Map<Character, Integer> map = new HashMap<>();

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

      // if the map already contains char, then increase the value by 1
      if (map.containsKey(str.charAt(i))) {
        map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
      } else { // else put the char into a map for the first time and add value of 1 as the number of occurrences
        map.put(str.charAt(i), 1);
      }
    }
    System.out.println(map);
  }
}
Output: {a=3, d=2, e=1, h=1, i=1, j=2, m=2, o=4, q=2, r=1, s=2, u=1, v=2}

How to count occurences of a specific char in a Java String?

Below is the program that counts occurrences of a specific char in a String.

class Test {

  public static void main(String[] args) {
    int count = 0;
    String str = "moiujjmhrqdoasdsooqavvae";

    // count occurrences of a char 'o'
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == 'o') {
        count++;
      }
    }

    System.out.println("Character 'o' occurred: " + count + " times.");
  }
}
Output: Character ‘o’ occurred: 4 times.

Leave a Reply

Your email address will not be published.