LearnFrenzy
Sign in Take a free test

std::string · String Programs · Question 5

Character frequency with std::map in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Count how often each letter occurs in a word (case-insensitive) using std::map, and print the letters in alphabetical order with their counts.

Solution
main.cpp
#include <cctype>
#include <iostream>
#include <map>
#include <string>

int main() {
    std::string s = "Programming";
    std::map<char, int> freq;
    for (unsigned char c : s)
        ++freq[static_cast<char>(std::tolower(c))];
    for (const auto& [ch, n] : freq)
        std::cout << ch << '=' << n << ' ';
    std::cout << '\n';
    return 0;
}

Output Verified by compiling and running

a=1 g=2 i=1 m=2 n=1 o=1 p=1 r=2

map::operator[] creates a counter at 0 the first time a key is seen. A std::map keeps keys sorted, so the output is alphabetical.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links