C program to count occurrences of a word in a string

C program to count occurrences of a word in a string

  • In this tutorial, we will learn a new program that is to count the occurrences of a particular word on to the string given.
  • Word counter
  • String: Collection of character.

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 word in 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 next word same as above.
  • This process continues till we encounter the end of a string.
  • In the end, we have a count of the occurrences of word into string.

Example:

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.

Program:

C program to count occurrences of a word in a string

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#include<stdio.h>#include<string.h>void main(){int str_len,word_len,i,j,k,flag,count=0;char str[200],word[20];printf(“Enter string: \n”);gets(str);printf(“Enter the word to count: \n”);scanf(“%s”,&word);str_len=strlen(str);word_len=strlen(word);for(i=0;i<str_len;i++){if(str[i]==word[0]&&((str[i-1]==’ ‘||i==0)&&(str[i+word_len]==’ ‘||str[i+word_len]==’ ‘))){for(flag=0,k=i+1,j=1;j<word_len;j++,k++){if(str[k]==word[j]) //checking letters in word with string word{flag++; //increment flag}}if(flag==word_len-1){count++;}}}printf(“Number of occurrence of ‘%s’ = %d”,word,count);}

Output: