This C Program counts the number of all repeated words in a string and displays the repeated words with it’s frequency.
Here is a source code of the C program that counts the number of all repeated words in a string display the word with it’s frequency. 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 all Repeated Words
* in a String & Display the Word with its Frequency
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
struct detail
{
char word[20];
int freq;
};
int update(struct detail [], const char [], int);
int main()
{
struct detail s[10];
char string[100], unit[20], c;
int i = 0, freq = 0, j = 0, count = 0, num = 0;
for (i = 0; i < 10; i++)
{
s[i].freq = 0;
}
printf("Enter string: ");
i = 0;
do
{
fflush(stdin);
c = getchar();
string[i++] = c;
} while (c != '\n');
string[i - 1] = '\0';
printf("The string entered is: %s\n", string);
for (i = 0; i < strlen(string); i++)
{
while (i < strlen(string) && string[i] != ' ' && isalnum(string[i]))
{
unit[j++] = string[i++];
}
if (j != 0)
{
unit[j] = '\0';
count = update(s, unit, count);
j = 0;
}
}
printf("*****************\nWord\tFrequency\n*****************\n");
for (i = 0; i < count; i++)
{
printf("%s\t %d\n", s[i].word, s[i].freq);
if (s[i].freq > 1)
{
num++;
}
}
printf("The number of repeated words are %d.\n", num);
return 0;
}
int update(struct detail s[], const char unit[], int count)
{
int i;
for (i = 0; i < count; i++)
{
if (strcmp(s[i].word, unit) == 0)
{
s[i].freq++;
return count;
}
}
/*If control reaches here, it means no match found in struct*/
strcpy(s[count].word, unit);
s[count].freq++;
/*count represents the number of fields updated in array s*/
return (count + 1);
}
$ cc wordfrequency.c $ ./a.out Enter string: hello world hello program hello C The string entered is: hello world hello program hello C ***************** Word Frequency ***************** hello 3 world 1 program 1 C 1 The number of repeated words are 1.
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
Next Steps:
- 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
Related Posts:
- Buy C Books
- Apply for C Internship
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Buy Computer Science Books