How to find the frequency of every character in a string with C++

1 Answer

0 votes
#include <iostream>
#include <unordered_map>
#include <string>

std::unordered_map<char, int> char_frequency(const std::string& str) {
    std::unordered_map<char, int> frequency;

    for (char charac : str) {
        frequency[charac]++;
    }

    return frequency;
}

int main() {
    std::string str = "C++ is a general-purpose programming language";
    std::unordered_map<char, int> result = char_frequency(str);

    for (const auto& pair : result) {
        std::cout << pair.first << " " << pair.second << std::endl;
    }
}



/*
run: 
 
m 2
o 2
u 2
C 1
l 2
  5
a 5
n 3
i 2
s 2
- 1
g 5
+ 2
e 4
r 4
p 3
 
*/

 



answered Nov 25, 2024 by avibootz

Related questions

1 answer 112 views
2 answers 118 views
2 answers 126 views
1 answer 131 views
1 answer 149 views
2 answers 153 views
...