Omar Samy Omar Samy - 1 month ago 8
C++ Question

how do I count letters and print them out beside their number of counting?

I want to do a program with c++ that reads a string and counts the letters in it and print out the letter with the maximum number of occurrence beside that number for example if the string was "ababcda" it will output 3 a the number of occurrence of a which is the maximum letter occurred in the string .
I have tried alot but I can't solve it.

Answer

Alternative solution to using map is by using vector

vector<int> v;

// initialize vector
for(int i = 'A'; i <= 'z'; i++) {
    v.push_back(0);
}

// increment count
for(int i = 0; i < str.size(); i++) {
    v[str[i] - 'A']++;
}

// your answer
// sort in descending order
sort(v.begin(), v.end(), greater<int>());
int ans = v[0];

Share what you have tried so that people can tell you what you did wrong.

Comments