1. Introduction
In this tutorial, we will learn how to count the occurrence of each character in a string using Java. This is a common problem that can help us understand how often each character appears in a given text, which can be useful for tasks such as text analysis, cryptography, and data compression.
2. Program Steps
1. Define the main method as the program’s entry point.
2. Initialize a string that we want to analyze.
3. Create a HashMap to store each character of the string and its corresponding occurrence count.
4. Loop through each character of the string.
5. For each character, check if it is already in the map. If it is, increment its count, otherwise, add it to the map with a count of 1.
6. Display the contents of the map, which will show the count of each character in the string.
3. Code Program
import java.util.HashMap;
public class CharacterCount {
public static void main(String[] args) {
// Step 2: Initialize a string that we want to analyze
String str = "programming";
// Step 3: Create a HashMap to store each character and its occurrence count
HashMap<Character, Integer> charCountMap = new HashMap<>();
// Step 4: Loop through each character of the string
for (char c : str.toCharArray()) {
// Step 5: Check if the character is already in the map
if (charCountMap.containsKey(c)) {
// If it is, increment its count
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
// Otherwise, add the character to the map with a count of 1
charCountMap.put(c, 1);
}
}
// Step 6: Display the contents of the map
System.out.println("Character Count: " + charCountMap);
}
}
Output:
Character Count: {a=1, g=2, i=1, m=2, n=1, o=1, p=1, r=1}
4. Step By Step Explanation
– Step 1: The main method is defined as the starting point of the program.
– Step 2: The string str is initialized with the value "programming".
– Step 3: A HashMap named charCountMap is created to store each character and its count.
– Step 4: A for-each loop is used to iterate over each character of the string str.
– Step 5: For each character, the program checks whether it is already in the map. If the character is present, its count is incremented. If not, it is added to the map with a count of 1.
– Step 6: The character count for each character in the string is displayed.
In this program, we successfully count the occurrence of each character in the string "programming" using a HashMap in Java.