【发布时间】:2015-01-28 15:08:20
【问题描述】:
到目前为止,我的代码有问题。我研究了有关 stackoverflow 的主题并找到了解决方案,但这些似乎不起作用。这是我的代码:
#include <stdio.h>
#include <string.h>
int main() {
char sentence[1000];
char word[100];
int count=0;
fgets(sentence, 999, stdin);
fgets(word, 99, stdin);
int word_len=strlen(word);
char *p;
for(p=(char*)sentence; (p=strstr(p, word)); p+=word_len)
{
++count;
}
printf("%d", count);
return 0;
}
但是不管这个词在句子中出现多少次,它在任何情况下都会打印出 1。有什么帮助吗?
【问题讨论】:
-
从
word中删除换行符。 -
您在每个 char 数组中浪费了 1 个字节。您可以在调用 fgets() 时使用整个数组大小:
fgets(sentence, sizeof sentence, stdin); -
嗯...“aba”在“abababa”中存在多少次?两个还是三个?
-
如果您删除换行符,您的代码可以工作。
-
"...在任何情况下都会打印出 1" 确定吗?
标签: c string numbers find substring