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

Download  Run Code

Output:

{g: 1}
{l: 1}
{d: 1}
{i: 2}
{t: 2}
{e: 3}
{c: 1}
{h: 2}

2. Using Range-based for-loop

Download  Run Code

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++.