Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Count of strings with frequency of each character at most K
Next article icon

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

Last Updated : 26 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

CPP




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
void printFrequency(string str)
{
    // Define an unordered_map
    unordered_map<char, int> M;
 
    // Traverse string str check if
    // current character is present
    // or not
    for (int i = 0; str[i]; i++)
    {
        // If the current characters
        // is not found then insert
        // current characters with
        // frequency 1
        if (M.find(str[i]) == M.end())
        {
            M.insert(make_pair(str[i], 1));
        }
 
        // Else update the frequency
        else
        {
            M[str[i]]++;
        }
    }
 
    // Traverse the map to print the
    // frequency
    for (auto& it : M) {
        cout << it.first << ' ' << it.second << '\n';
    }
}
 
// Driver Code
int main()
{
    string str = "geeksforgeeks";
 
    // Function call
    printFrequency(str);
    return 0;
}
 
 
Output
r 1 e 4 s 2 g 2 k 2 f 1 o 1 


Next Article
Count of strings with frequency of each character at most K

H

hrishikeshkonderu
Improve
Article Tags :
  • C++
  • cpp-strings
  • cpp-unordered_map
  • frequency-counting
  • STL
Practice Tags :
  • CPP
  • cpp-strings
  • STL

Similar Reads

  • Count of substrings of given string with frequency of each character at most K
    Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K. Examples: Input: str = "abab", K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are "a", "b", "a
    6 min read
  • Check if frequency of characters are in Recaman Series
    Given a string of lowercase alphabets. The task is to check whether the frequency of alphabets in this string, after arranging in any possible manner, forms the Recaman's Sequence(excluding the first term).Print "YES" if they are in sequence, otherwise output "NO".Few starting terms of Recaman's Seq
    8 min read
  • Find frequency of each character with positions in given Array of Strings
    Given an array, arr[] consisting of N strings where each character of the string is lower case English alphabet, the task is to store and print the occurrence of every distinct character in every string. Examples:  Input: arr[] = { "geeksforgeeks", "gfg" }Output: Occurrences of: e = [1 2] [1 3] [1 1
    7 min read
  • Print the frequency of adjacent repeating characters in given string
    Given a string str of length N. The task is to print the frequency of adjacent repeating characters. Examples: Input: str = "Hello"Output: l: 2Explanation: Consecutive Repeating Character from the given string is "l" and its frequency is 2. Input: str = "Hellolllee"Output: l: 2 l: 3 e: 2Explanation:
    5 min read
  • Count of strings with frequency of each character at most K
    Given an array arr[] containing N strings and an integer K, the task is to find the count of strings with the frequency of each character at most K Examples: Input: arr[] = { "abab", "derdee", "erre" }, K = 2Output: 2Explanation: Strings with character frequency at most 2 are "abab", "erre". Hence c
    6 min read
  • How to create an unordered_map of user defined class in C++?
    unordered_map is used to implement hash tables. It stores key value pairs. For every key, a hash function is computed and value is stored at that hash entry. Hash functions for standard data types (int, char, string, ..) are predefined. How to use our own data types for implementing hash tables?unor
    3 min read
  • Check whether two strings are anagrams of each other using unordered_map in C++
    Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Unordered Map can
    3 min read
  • Count the number of unique characters in a given String
    Given a string, str consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: str = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}. Inp
    14 min read
  • Generate a Number in Decreasing order of Frequencies of characters of a given String
    Given a string Str of length N, consisting of lowercase alphabets, the task is to generate a number in decreasing order of the frequency of characters in the given string. If two characters have the same frequency, the character with a smaller ASCII value appears first. Numbers assigned to character
    12 min read
  • String with frequency of characters in Lucas Sequence
    Given a string 'str' containing lowercase English alphabets, the task is to find whether the frequencies of the characters of the string are in Lucas sequence or not. You are free to arrange the frequency numbers in any way, in order to form the Lucas sequence. If possible then print YES otherwise N
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences