
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Occurrence of Each Character in a String in Java
To find the occurrence of each character in a string we can use the Map utility of Java. In Map a key cannot be duplicated so make each character of the string a key of Map and provide the initial value corresponding to each key as 1 if this character is not inserted in Map before. Now when a character repeats during insertion as a key in Map increases its value by one. Continue this for each character until all characters of the string get inserted.
Problem Statement
Write a program in Java to check the occurrence of each character in the string.
Input
str = "SSDRRRTTYYTYTR"
Output
{D=1, T=4, S=2, R=4, Y=3}
Steps to check occurrence of each character in string
Following are the steps to check the occurrence of each character in String
- Initialize the string by defining a string str containing the characters to be counted.
- Create a HashMap by initializing a HashMap to store character occurrences.
- Iterate over the string using a for loop from the end to the beginning.
- Check if the character is already on the map if so, increment the count. Otherwise, add the character with an initial count of 1.
- Print the result.
Java program to check occurrence of each character in string
Below is the Java program to check the occurrence of each character in the String ?
public class occurenceOfCharacter { public static void main(String[] args) { String str = "SSDRRRTTYYTYTR"; HashMap <Character, Integer> hMap = new HashMap<>(); for (int i = str.length() - 1; i > = 0; i--) { if (hMap.containsKey(str.charAt(i))) { int count = hMap.get(str.charAt(i)); hMap.put(str.charAt(i), ++count); } else { hMap.put(str.charAt(i),1); } } System.out.println(hMap); } }
Output
{D=1, T=4, S=2, R=4, Y=3}
Code Explanation
This program counts the occurrences of each character in the string str using a HashMap. The string "SSDRRRTTYYTYTR" is processed in reverse order by iterating from the last character to the first. For each character, the program checks if it already exists in the HashMap. If it does, the count is incremented. If not, the character is added to the map with an initial count of 1. The final HashMap is then printed, showing the number of occurrences for each character. For example, 'T' occurs 4 times, and 'S' occurs 2 times.