简体   繁体   中英

Counting most frequent character in a string

I have a complex C program, and i wanna write only a function which gets a string as a parameter.

int most_frequent(char *string)

The function has to return the number of the most frequent character in the string. I tried something like this, but this is incorrect i think:

 int most_frequent(char *string){
     int i, lenght;
     lenght=strlen(string);
     int max=0, x=0;
     for(i=0;i<lenght;i++)
     {
         if(string[i]==string[i++])
         {
             x++;
         }
         if(max<x)
             max=x;
     }
     return max;
 }

for example: "overflow" - 2 "eleven" - 3

I assume that you have a string that follows ASCII. In this way, there are 256 possible values for each char. Thus we count the frequency of each and return the largest one.

int most_frequent(char *string){
     int count[256] = {0}; // Assum char is ASCII
     int max = 0;
     int i;

     for(i=0; i < strlen(string) ;i++) {
         count[(unsigned char)(string[i])] ++;
     }

     for(i=0; i < 256 ;i++) {
         if (count[i] > max) 
             max = count[i];
     }
     return max;
 }

Do following:

// version that ignores the upper and lower case
int most_frequent(char *string) {
    int letterCout[26];

    // counts occurrence of each letter 
    for (int i = 0; i < strlen(string); ++i){
       // this counts characters if you are ignoring the case (upper or lower)
       if (string[i] >= 'a' && string[i] =< 'z')
           alphabet [string[i] - 'a']++;
       else if (string[i] >= 'A' && string[i] =< 'Z')
           alphabet [string[i] - 'A']++;
    }

    // finds which letter occurred the most
    int max = 0;
    for (int i = 0; i < strlen(string); ++i)
        if (letterCoutn[i] > max)
            max = letterCount[i];

    return max;
}

or you can do this:

// version which does not ignore case but count the separately
int most_frequent(char *string) {
    int letterCout[52];  // 52 so you can count upper and lower case

    // counts occurrence of each letter 
    for (int i = 0; i < strlen(string); ++i){
       if (string[i] >= 'a' && string[i] <= 'z')
           alphabet [string[i] - 'a' + 26]++; // plus 26 so to offset in array so upper case could be counted in lower half of an array.
       else if (string[i] >= 'A' && string[i] <= 'Z')
           alphabet [string[i] - 'A']++;
    }

    // finds which letter occurred the most
    int max = 0;
    for (int i = 0; i < strlen(string) * 2; ++i)
        if (letterCoutn[i] > max)
            max = letterCount[i];

    return max;
}

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