Here's the code to count occurencies of each character in a string:
int cnt[1000];
string s = "fooooobar";
for (char i : s) cnt[i]++;
cout << cnt['o'] << '\n';
cout << cnt['a'] << '\n';
cout << cnt['r'] << '\n';
cout << cnt['b'] << '\n';
Output 1:
5
1
33262
129355441
Output 2:
5
1
33262
328199857
Output 3:
5
1
33262
-1913409871
Output 4:
5
1
33262
-826184015
How can I access an array of int
values indexing with a char
values to count specific occurrences of a character?
Why is the first 2 results are valid, the third one is invalid, and the fourth one is invalid and different every time?
I use a g++ compiler as follows:
g++ -std=c++11 -Wall filename.cpp -o