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}
 
This program creates a HashMap with characters as keys and integers as values. Then it uses a for loop to iterate through each character in the input string “moiujjmhrqdoasdsooqavvae”. Within the for loop, an if-else statement is used to check if the current character already exists in the map. If it does, the value of that character key is incremented by 1. If it does not, the character is added to the map with a value of 1. This allows the program to count the number of occurrences of each character in the input string. Finally, the program prints the map containing all the characters of the string as keys and their occurrences as values.

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. Required fields are marked *