Find frequency of all characters in a string in C++
This post will discuss how to find the frequency of all characters in a string in C++.
A simple and efficient solution is to create a frequency map. The idea is to iterate the string using std::for_each or range-based for-loop, and for each character, insert/update its count into a map. This works in linear time and takes space proportional to the total number of distinct characters present in the string.
1. Using std::for_each function
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <unordered_map> #include <algorithm> #include <string> #include <iostream> int main() { std::string str = "techiedelight"; std::unordered_map<char, int> freq; std::for_each(std::begin(str), std::end(str), [&freq](const char &c) { freq[c]++; }); for (auto &pair: freq) { std::cout << '{' << pair.first << ": " << pair.second << '}' << std::endl; } return 0; } |
Output:
{g: 1}
{l: 1}
{d: 1}
{i: 2}
{t: 2}
{e: 3}
{c: 1}
{h: 2}
2. Using Range-based for-loop
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <unordered_map> #include <algorithm> #include <string> #include <iostream> int main() { std::string str = "techiedelight"; std::unordered_map<char, int> freq; for (const char &c: str) { freq[c]++; } for (auto &pair: freq) { std::cout << '{' << pair.first << ": " << pair.second << '}' << std::endl; } return 0; } |
Output:
{g: 1}
{l: 1}
{d: 1}
{i: 2}
{t: 2}
{e: 3}
{c: 1}
{h: 2}
That’s all about finding the frequency of all characters in a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)