How To Count The Number Of Cccurrences Of Each Character In A String In Java
Chapter:
String Handling
Last Updated:
03-06-2023 13:16:54 UTC
Program:
/* ............... START ............... */
import java.util.HashMap;
import java.util.Map;
public class CharacterCount {
public static void main(String[] args) {
String str = "Hello, World!";
Map<Character, Integer> charCountMap = new HashMap<>();
// Iterate over each character in the string
for (char c : str.toCharArray()) {
// Check if the character is already in the map
if (charCountMap.containsKey(c)) {
// If it is, increment the count by 1
int count = charCountMap.get(c);
charCountMap.put(c, count + 1);
} else {
// If it is not, add it to the map with a count of 1
charCountMap.put(c, 1);
}
}
// Print the character count
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println("'" + entry.getKey() + "' occurs " + entry.getValue() + " times");
}
}
}
/* ............... END ............... */
Output
'H' occurs 1 times
'e' occurs 1 times
'l' occurs 3 times
'o' occurs 2 times
',' occurs 1 times
' ' occurs 1 times
'W' occurs 1 times
'r' occurs 1 times
'd' occurs 1 times
'!' occurs 1 times
Notes:
-
This program counts the number of occurrences of each character in a given string in Java. It utilizes a HashMap to store the characters as keys and their counts as values, iterating over the string and updating the count for each character. Finally, it prints out the character count for each unique character in the string.
Tags
How to count the number of occurrences of each character in a string in Java #Java Program to Count the Occurrences of Each Character #Write a program to count the number of occurrences of character