C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Count Occurrences of a Word in a Sentence

C Program: Count Occurrences of a Word in a Sentence

C

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[200], word[50];

    char temp[200];

    int count = 0;

 

    printf("Enter a sentence: ");

    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove newline

 

    printf("Enter the word to find: ");

    scanf("%s", word);

 

    // Copy sentence to temp so strtok() won't modify the original string

    strcpy(temp, str);

 

    char *token = strtok(temp, " ");

    while (token != NULL) {

        if (strcmp(token, word) == 0) {

            count++;

        }

        token = strtok(NULL, " ");

    }

 

    printf("\nThe word '%s' occurs %d time(s) in the sentence.\n", word, count);

 

    return 0;

}

Output

 
OUTPUT :
Enter a sentence: This is a test and this is simple
Enter the word to find: is

The word 'is' occurs 2 time(s) in the sentence.

Explanation

  • Reads a sentence using fgets() and a target word using scanf().
  • Uses strtok() to split the sentence into words (separated by spaces).
  • Compares each word with the target word using strcmp().
  • Counts how many times the word appears.