简体   繁体   中英

C program to find number of occurrences of substring in string

I have a problem with my code so far. I researched the topic on stackoverflow and found solutions but those don't seem to work. Here is my code:

#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;
}

But it prints out 1 in any case, no matter how many times the word is found in the sentence. Any help?

change to

....
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)
....

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