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

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>

/* find most frequent letter in a string */
char mostFrequentLetter(const char *s) {
    int freq[26] = {0};   /* frequency array */

    /* count only alphabetic characters */
    for (const char *p = s; *p; p++) {
        if (isalpha((unsigned char)*p)) {
            freq[tolower((unsigned char)*p) - 'a']++;
        }
    }

    /* find index of max frequency */
    int maxIndex = 0;
    for (int i = 1; i < 26; i++) {
        if (freq[i] > freq[maxIndex]) {
            maxIndex = i;
        }
    }

    return (char)('a' + maxIndex);
}

int main(void) {
    const char *text = "abcabcaadbbccsedsade";

    char result = mostFrequentLetter(text);

    printf("Most frequent letter: %c\n", result);

    return 0;
}


/*
run:

Most frequent letter: a

*/

 



answered 3 days ago by avibootz

Related questions

...