简体   繁体   中英

Getting most frequent characters in array in c

I am trying to get the most frequent characters from an array.

Here's my code

#include <stdio.h>

int main(void)
{
    int c[1000];
    char input[] = "abcdab";    
    int i;

    for(i=0; input[i]; i++)
    {
        c[input[i]]++; 
    }

    int j = 0;
    char str = 0;

    for(i=0; i<256; i++)
    {
        if(c[i] > j)
        {
            j = c[i];
            str = i;
        } 
    }

    printf("%c\n", str); 
    return 0;
}

It returns 'a'

But I want to get 'a' and 'b' since they are the most frequent characters in the array. Any help would be appreciated, thank you.

You are passing through the entire array looking for a maximum, and remembering the first one. With the solution you have, you need an additional loop:

for(i=0; i<256; i++){ // Look for all maximums
    if(c[i] == j) // If it is the maximum
    {
         printf("%c\n", i); // print the character
    } 
}

Note that your array c is not initialized to all zeroes, so it is purely by chance (not really) that the code is working. If you want c to be all zeroes, you need to declare it as int c[1000] = {0}; or to call memset on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM