简体   繁体   中英

Count number of same letters in a string

I have been reading "The C Programming Language" and I got to this problem, that my output is 0 for any given string I send.

My function looks like this:

 int number_of_repeating(char *word,char k){
    int b=0,len=0,i;
    gets(word);
    len=strlen(word);
    for(i=0;i<len;i++){
        if(word[i]==k)
        b++;
    }
    return  b;
}

Problem :

I send him word for example: Jhonny , and character n , so it should count number of n's in the word (in this case the output should be 2).

What am I doing wrong?

#include <stdio.h>
int number_of_repeating(char *word,char k){
    int b=0,len=0,i;
    gets(word); //<------- You need to remove this one because it may overwrite
    len=strlen(word);
    for(i=0;i<len;i++){
        if(word[i]==k)
        b++;
    }
    return  b;
}
int main(void) {
    // your code goes here
    printf("%d",number_of_repeating("johnny",'n'));
    return 0;
}

如果在传递字符串时没有理由调用gets(),则可能是它,或者您的类型可能是错误的。

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