C program to count occurrences of a word in a string: To count the occurrences of a particular word count on to the string given.
Example:
String: The Technical Seek is the technical site
Word to count: technical
The number of occurrences of the word is = 2

Algorithm to count occurrences of a word in a string

  1. Take the Input string str
  2. Input word to which you want to count occurrences find
  3. Declare counter count=0
  4. Traverse the string from start to end
    if a character is a space
    new_var= all character till space
    if new_var== find
    count++
    else
    continue

C program to count occurrences of a word in a string

#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:

C program to count occurrences of a word in a string

Write A Comment