Given a string, the task is to write a program in Java which prints the number of occurrences of each character in a string.
Examples:
Input: str = "GeeksForGeeks"
Output:
r 1
s 2
e 4
F 1
G 2
k 2
o 1
Input: str = "Ajit"
Output:
A 1
t 1
i 1
j 1
An approach using frequency[] array has already been discussed in the previous post. In this program an approach using Hashmap in Java has been discussed.
- Declare a Hashmap in Java of {char, int}.
- Traverse in the string, check if the Hashmap already contains the traversed character or not.
- If it is present, then increase its count using get() and put() function in Hashmap.
- Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.
Below is the implementation of the above approach.
Java
import java.io.*;
import java.util.*;
class OccurrenceOfCharInString {
static void characterCount(String inputString)
{
HashMap<Character, Integer> charCountMap
= new HashMap<Character, Integer>();
char [] strArray = inputString.toCharArray();
for ( char c : strArray) {
if (charCountMap.containsKey(c)) {
charCountMap.put(c, charCountMap.get(c) + 1 );
}
else {
charCountMap.put(c, 1 );
}
}
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
public static void main(String[] args)
{
String str = "Ajit" ;
characterCount(str);
}
}
|
Time complexity: O(n) where n is length of given string
Auxiliary Space: O(n)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Dec, 2022
Like Article
Save Article