How to count the occurrence of the spaces and any ASCII characters in a string with C++

1 Answer

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

int main()
{
    std::string str = "C++ is a high-level, general-purpose programming language created by Danish computer scientist Bjarne Stroustrup";

    std::map<char, int> occurrences;

    for (std::string::iterator character = str.begin(); character != str.end(); character++) {
        occurrences[*character] += 1;
    }

    for (std::map<char, int>::iterator entry = occurrences.begin(); entry != occurrences.end(); entry++) {
        std::cout << entry->first << '=' << entry->second << std::endl;
    }
}


/*
run:

 =13
+=2
,=1
-=2
B=1
C=1
D=1
S=1
a=8
b=1
c=3
d=1
e=11
g=6
h=3
i=6
j=1
l=4
m=3
n=6
o=4
p=5
r=9
s=6
t=6
u=5
v=1
y=1

*/

 



answered Sep 16, 2024 by avibootz
...