String Exercises
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. Logic to count occurrences of a word in given string.
Required knowledge
Basic C programming, C if-else, C for loop, Array, functions, Strings
Logic to count occurrences of a word in given string
Below is the step by step descriptive logic to count occurrences of a word in given string.
- 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.
Program to count occurrences of a word
/** * C program to count occurrences of a word in a given string */ #include <stdio.h> #include <string.h> #define MAX_SIZE 100 // Maximum string size /* Function declaration */ int countOccurrences(char * str, char * toSearch); int main() { char str[MAX_SIZE]; char toSearch[MAX_SIZE]; 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 i, j, found, count; int stringLen, searchLen; stringLen = strlen(str); // length of string searchLen = strlen(toSearch); // length of word to be searched count = 0; for(i=0; i <= stringLen-searchLen; i++) { /* Match word with string */ found = 1; for(j=0; j<searchLen; j++) { if(str[i + j] != toSearch[j]) { found = 0; break; } } if(found == 1) { count++; } } return count; }