How to find the second most frequent character in a string with C

1 Answer

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

char GetSecondMostFrequentChar(char s[]) {
    int count[256] = { 0 }; // 256 = ASCII table size
    size_t size = strlen(s);
  
    for (int i = 0; i < size; i++) {
        count[s[i]]++;
    }

    int first = 0, second = 0;

    for (int i = 0; i < 256; i++) {
        if (count[i] > count[first]) {
            second = first;
            first = i;
        }
        else if (count[i] > count[second] && count[i] != count[first]) {
            second = i;
        }
    }

    return second;
}

int main() {
    char str[] = "bbaddddccce";

    printf("%c", GetSecondMostFrequentChar(str));

    return 0;
}




/*
run:

c

*/

 



answered Aug 31, 2022 by avibootz
edited Aug 31, 2022 by avibootz

Related questions

1 answer 111 views
1 answer 134 views
2 answers 161 views
1 answer 114 views
1 answer 145 views
...