In this tutorial, we will learn a new program that is to count the occurrences of a particular word on to the string given.
Logic to count occurrences of a word in a string:
- First, we take the string. (full statement)
- We take the word which we want to find count from the given string.
- Take a variable count to store count of word occurrences.
- Then we start searching the occurrences of a word in the string.
- We start reading the character by character till we encounter the space if space encountered then we consider it as one word and store it to another variable.
- Then we check stored word with our taken word (which we searching in a string).
- If it matches we increment the count else not.
- Again, we continue by taking the next word same as above.
- This process continues until we encounter the end of a string.
- In the end, we have a count of the occurrences of a word into the string.
String: The Technical Seek is the technical site
Word to count: technical
The number of occurrences of the word is = 2
Now we will implement this program in c.
C program to count occurrences of a word in a string
printf("Enter string: \n");
printf("Enter the word to count: \n");
if(str[i]==word&&((str[i-1]==' '||i==0)&&(str[i+word_len]==' '||str[i+word_len]==' ')))
if(str[k]==word[j]) //checking letters in word with string word
flag++; //increment flag
printf("Number of occurrence of '%s' = %d",word,count);