【问题标题】:C program to find number of occurrences of substring in stringC程序查找字符串中子字符串的出现次数
【发布时间】: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


【解决方案1】:

改成

....
fgets(word, 99, stdin);
char *p = strchr(word, '\n');
if(p)
    *p = 0;
int word_len=strlen(word);
for(p=sentence; (p=strstr(p, word)); p+=word_len)
....

【讨论】:

  • 如果我使用 scanf %s 作为单词,它也可以工作,因为我不需要该字符串中的空格。感谢您的提示!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2010-12-25
  • 2011-10-16
  • 2015-06-10
  • 2014-03-28
相关资源
最近更新 更多