How to find the most frequent letter in a string with C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <cctype>

char mostFrequentLetter(const std::string &s) {
    std::vector<int> freq(26, 0);

    for (char c : s) {
        if (isalpha(c)) {
            freq[tolower(c) - 'a']++;
        }
    }

    int maxIndex = 0;
    for (int i = 1; i < 26; i++) {
        if (freq[i] > freq[maxIndex]) {
            maxIndex = i;
        }
    }

    return char('a' + maxIndex);
}

int main() {
    std::string text = "abcabcaadbbccsedsade";

    char result = mostFrequentLetter(text);
    
    std::cout << "Most frequent letter: " << result << std::endl;
}



/*
run:

Most frequent letter: a

*/

 



answered 2 days ago by avibootz

Related questions

...