Interview Questions   Tutorials   Discussions   Programs   

C - Write a C program to count the number of occurrence of a specific word in the given strings?




309
views
asked marvit August 18, 2014 09:08 AM  

Write a C program to count the number of occurrence of a specific word in the given strings?


           

1 Answers



 
answered By bhjahnavi   0  
/* program to find the number of occurrence of a specific word in the given string */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 int main()
{
  char string[100], word[20], unit[20], c;
  int i = 0, j = 0, count = 0;
 
  printf("Enter string: ");
  i = 0;
  do
  {
    fflush(stdin);
    c = getchar();
    string[i++] = c;
 
  } while (c != '\n');
  string[i - 1] = '\0';
  printf("Enter the word you want to find: ");
  scanf("%s", word);
  for (i = 0; i < strlen(string); i++)
  {
    while (i < strlen(string) && !isspace(string[i]) && isalnum(string[i]))
    {
      unit[j++] = string[i++];
    }
    if (j != 0)
    {
      unit[j] = '\0';
      if (strcmp(unit, word) == 0)
      {
        count++;
      }
      j = 0;
    }
  }
 
  printf("The number of times the word '%s' found in '%s' is '%d'.\n", word, string, count);
}
output:
Enter string: hai how are you
Enter the word you want to find: hai 
The number of times the word 'hai' found in 'hai how are you' is 1
flag   
   add comment

Your answer

Join with account you already have

FF

Preview


Ready to start your tutorial with us? That's great! Send us an email and we will get back to you as soon as possible!

Alert