[英]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. 我一直在阅读“ The C Programming Language”,但我遇到了这个问题,对于我发送的任何给定字符串,我的输出都是0
。
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). 我给他发送了一个单词,例如: Jhonny
和字符n
,因此它应该计算单词中n的个数(在这种情况下,输出应为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(),则可能是它,或者您的类型可能是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.