VOOZH about

URL: https://www.geeksforgeeks.org/cpp/frequency-of-each-character-in-a-string-using-unordered_map-in-c/

⇱ Frequency of each character in a String using unordered_map in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Frequency of each character in a String using unordered_map in C++

Last Updated : 12 Jul, 2025

Given a string str, the task is to find the frequency of each character of a string using an unordered_map in C++ STL.

Examples: 

Input: str = "geeksforgeeks" 
Output: 
r 1 
e 4 
s 2 
g 2 
k 2 
f 1 
o 1

Input: str = "programming" 
Output: 
n 1 
i 1 
p 1 
o 1 
r 2 
a 1 
g 2 
m 2 

Approach: 

  1. Traverse each character of the given string str.
  2. Check whether the current character is present in unordered_map or not.
  3. If it is present, then update the frequency of the current characters else insert the characters with frequency 1 as shown below: 
if(M.find(s[i])==M.end()) {
 M.insert(make_pair{s[i], 1});
}
else {
 M[s[i]]++;
}

        4. Traverse the unordered_map and print the frequency of each characters stored as a mapped value.

Below is the implementation of the above approach:


Output
r 1
e 4
s 2
g 2
k 2
f 1
o 1
Comment