Java program to count the occurrences of each character is used to find how many times every character appears in a string. It helps in understanding string manipulation and frequency counting in Java.
- Counts the frequency of each character in a given string.
- Commonly used in string processing and interview questions.
Example: Input/output to count the occurrences of each character.
Input: s = "Geeks"
Output: G = 1, e = 2, k = 1, s=1.Input: s = "Hello"
Output: H = 1, e= 1, l= 2, o= 1.
Naive Approach
In this approach, we manually compare each character of the string using nested loops and count their occurrences.
Algorithm
- Convert the string into a character array.
- Create a boolean array to track already counted characters.
- Traverse each character of the array one by one.
- If the current character is already counted, skip it.
- Compare the current character with the remaining characters using another loop.
- If a match is found, increment the count and mark that character as counted.
- Print the character along with its occurrence count.
class Geeks{
public static void main(String[] args) {
String s = "Program";
char[] ch = s.toCharArray();
boolean[] b = new boolean[s.length()];
System.out.println("Character Occurrences:");
for (int i = 0; i < ch.length; i++) {
if (b[i]) continue; // Skip already counted characters
int c = 1;
for (int j = i + 1; j < ch.length; j++) {
if (ch[i] == ch[j]) {
c++;
b[j] = true; // Mark character as counted
}
}
System.out.println(ch[i] + " : " + c);
}
}
}
Output
Character Occurrences: P : 1 r : 2 o : 1 g : 1 a : 1 m : 1
Explanation: The above example uses a "b" Boolean array to track counted characters. Then, nested loops iterate over the character array to calculate occurrences.
Other Methods to Count the Occurrences of Each Character
Using Counter Array
This approach uses an integer array indexed by ASCII values. to directly count the frequency of each character in a string.
Algorithm:
- Create an integer array of size 256 to store frequency of ASCII characters.
- Traverse the string character by character.
- Convert each character to its ASCII value.
- Use ASCII value as index and increment the count in the array.
- After traversal, iterate through the array and print characters with frequency > 0.
class Geeks
{
public static void main(String[] args) {
String s = "Program";
int[] c = new int[256]; // Array for ASCII characters
// Increment count for each character
for (char ch : s.toCharArray()) {
c[ch]++;
}
System.out.println("Character Occurrences:");
// Print characters with non-zero counts
for (int i = 0; i < c.length; i++) {
if (c[i] > 0) {
System.out.println((char) i + " : " + c[i]);
}
}
}
}
Output
Character Occurrences: P : 1 a : 1 g : 1 m : 1 o : 1 r : 2
Explanation: In the above example, the ASCII value of each character acts as the index in the counter array. The program prints only non-zero counts by representing the character frequencies. This is efficient for ASCII characters but not suitable for Unicode.
Using Java HashMap
This approach uses a HashMap to dynamically store characters as keys and count their occurrences as values.
Algorithm:
- Create a HashMap to store each character as key and its frequency as value.
- Traverse the string character by character.
- If the character already exists in the map, increment its count.
- If the character does not exist, add it to the map with initial value 1.
- After traversal, iterate through the HashMap and print each character with its frequency.
import java.util.HashMap;
import java.util.Map;
class Geeks
{
public static void main(String[] args) {
String s = "Programming";
Map<Character, Integer> countMap = new HashMap<>();
for (char c : s.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1); // Update count
}
System.out.println("Character Occurrences:");
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Output
Character Occurrences: P : 1 a : 1 r : 2 g : 2 i : 1 m : 2 n : 1 o : 1
Explanation: In the above example, the HashMap stores characters as keys and their frequencies as values. The getOrDefault() method simplifies updating the count for each character. This approach is efficient and works for both ASCII and Unicode strings.
Using Java 8 Streams
This approach uses Java 8 Streams to group characters and count their occurrences in a concise and functional way.
Algorithm:
- Convert the string into a stream using chars() method (returns IntStream of ASCII values).
- Use mapToObj() to convert integer values into character objects.
- Use Collectors.groupingBy() to group same characters together.
- Use Collectors.counting() to count occurrences of each character.
- Store the result in a Map where key = character and value = frequency.
- Print the Map to display character frequencies.
import java.util.Map;
import java.util.stream.Collectors;
class Geeks
{
public static void main(String[] args) {
String s = "Programming";
Map<Character, Long> countMap = s.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println("Character Occurrences:");
countMap.forEach((k, v) -> System.out.println(k + " : " + v));
}
}
Output
Character Occurrences: P : 1 a : 1 r : 2 g : 2 i : 1 m : 2 n : 1 o : 1
Explanation: In the above example, the chars() method creates a stream of character codes from the string. The groupingBy collector groups characters and counts their occurrences. This is a modern and concise solution but is the slightly slower due to stream overhead.