This is a C Program to count the number of repeated occurrences of a particular word in a string.
This C Program counts the number of repeated occurrences of a particular word in a string.
Take input from the user and performs string operations to count the repeated occurrences of a particular word as shown in the program below.
Here is a source code of the C program that counts the number of repeated occurrences of a particular word in a string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Count the Number of Repeated Occurrences * of a particular Word in a 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); }
In this C Program, we are reading the word to find using the ‘word’ variable. For loop is used to count the number of repeated occurrences of a particular word in a string.
While loop is used to check that the length, space, and alphanumeric number string is less than the occurring string. If the condition is true, then execute the iteration of the loop. If condition statement is used to check that the value of ‘j’ variable is not equal to 0.
If the condition is true then execute the statement, if statement is used to check that the string compared is equal to 0. If the condition is true then execute the statement. Print number of repeated occurrences of a particular word in a string.
$ cc givenword.c $ ./a.out Enter string: hello world hello program hello C Enter the word you want to find: hello The number of times the word 'hello' found in 'hello world hello program hello C' is 3.
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Watch Advanced C Programming Videos
- Buy C Books
- Practice BCA MCQs
- Practice Computer Science MCQs
- Apply for Computer Science Internship