Enter n strings, separated by spaces. There are repeated occurrences of these strings. Now count the number of occurrences of each string and find the string with the most occurrences.

#include<stdio.h>
#include<string.h>
int main(){
    int i,n,j,k;
    k = 0 ;
    char str [ 100 ] [ 100 ];
    int len ​​[ 100 ], book [ 100 ];
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%s",str[i]);
        len [i] = 1 ;
        book[i]=0;
    }
    for(i=0;i<n;i++){
        for(j=i+1;j<n;j++){
            if(strcmp(str[i],str[j])==0){
                len [i] ++ ;
                book[j]=1;
            }
        }
    }
    for(i=0;i<n;i++){
        if(k<len[i]){
            k=i;
        }
    }
    for(i=0;i<n;i++){
        if(book[i]==0){
            puts(str[i]);
            printf("%d\n",len[i]);
        }
    }
    printf("\n");
    printf( " The most frequent string\n " );
    puts(str[k]);
    return 0;

}

You don't need to use gets, just scanf_s directly, ' ' does not need to read ' ', (I'm stupid.......)

book[] is used to mark duplicates, in order not to duplicate the output.

str[][] string, two-dimensional array can be used to store strings, but it is easy for people to waste memory, or it will burst the stack.

len[] is used to count the number of times, and the subscript is the same as that of the string.

When I have time, I will look into using dynamic arrays and give it a try.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326002915&siteId=291194637