C++ How To Count Character Frequency
Count Character Frequency
Use a map to count how many times each character appears in a string:
Example
string text = "hello";
map<char, int> count;
for (char c : text) {
count[c]++;
}
for (auto item : count) {
cout << item.first << ": " << item.second << "\n";
}
Explanation:count[c]++ adds 1 to the count for the character c. If the character is not in the map yet, it starts at 0.
A map keeps its keys sorted, so the characters are printed in alphabetical order.