How to count the occurrences of a word in a string using C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
 
int countOccurrences(const char* s, const char* word) {
    int count = 0;
    const char* temp = s;
     
    while ((temp = strstr(temp, word)) != NULL) {
        count++;
        temp += strlen(word);
    }
     
    return count;
}
 
int main() {
    const char* s = "cprogramming cprogramming c++ c# c++ cprogramming c# cprogramming";
    const char* word = "cprogramming";
     
    printf("Occurrences of '%s': %d\n", word, countOccurrences(s, word));
     
    return 0;
}
 
 
 
/*
run:
 
Occurrences of 'cprogramming': 4
 
*/

 



answered Apr 2, 2019 by avibootz
edited Mar 1, 2025 by avibootz

Related questions

1 answer 264 views
1 answer 200 views
1 answer 285 views
1 answer 245 views
3 answers 290 views
3 answers 296 views
1 answer 256 views
...