C Programming Code Examples C > Strings Code Examples program to count occurrences of a word in a string program to count occurrences of a word in a string Write a C program to count occurrences of a word in a given string using loop. How to count total occurrences of a given word in a string using loop in C programming. Input string from user, store it in some variable say str. Input word to be searched from user, store it in some other variable say word. Initialize a counter variable to store total word match count i.e. say count = 0. Run a loop from start of the string str to end. Inside loop for each character in word match the rest of characters with str. If a word match is found in case increment count = count + 1. #include <stdio.h> #include <string.h> #define maxsize 100 // Maximum string size /* Function declaration */ int countOccurrences(char * str, char * toSearch); int main() { char str[maxsize]; char toSearch[maxsize]; int count; /* Input string and word from user */ printf("Enter any string: "); gets(str); printf("Enter word to search occurrences: "); gets(toSearch); count = countOccurrences(str, toSearch); printf("Total occurrences of '%s': %d", toSearch, count); return 0; } /** Get, total number of occurrences of a word in a string */ int countOccurrences(char * str, char * toSearch) { int x, j, found, count; int stringLen, searchLen; stringLen = strlen(str); // length of string searchLen = strlen(toSearch); // length of word to be searched count = 0; for(x=0; x <= stringLen-searchLen; x++) { /* Match word with string */ found = 1; for(j=0; j<searchLen; j++) { if(str[x + j] != toSearch[j]) { found = 0; break; } } if(found == 1) { count++; } } return count; }