Find the frequency of all words in a string
C program to find the frequency of all words in a given string.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 50
int split_words(char str[MAX], char words[MAX][MAX])
{
int i, j, count;
char prev_char;
i = 0;
j = 0;
count = 0;
prev_char = '\0';
while(1)
{
if(str[i] == ' ' || str[i] == '\t' || str[i] == '\0')
{
if(prev_char!=' ' && prev_char!='\t' && prev_char!='\0')
{
words[count][j] = '\0';
count++;
j = 0;
}
}
else
{
words[count][j] = str[i];
j++;
}
prev_char = str[i];
if(str[i] == '\0')
break;
else
i++;
}
return(count);
}
void main()
{
char str[MAX];
char words[MAX][MAX];
char uniq_words[MAX][MAX];
int freq[MAX];
int count, i, j, uniq_count;
printf("Enter the string\t:");
gets(str);
count = split_words(str, words);
uniq_count = 0;
for(i=0;i<count;i++)
{
if(words[i][0] != '\0')
{
strcpy(uniq_words[uniq_count],words[i]);
freq[uniq_count] = 1;
for(j=i+1;j<count;j++)
{
if(strcmp(words[i],words[j]) == 0)
{
freq[uniq_count]++;
words[j][0] = '\0';
}
}
uniq_count++;
}
}
printf("\nWord\t\tFrequency\n\n");
for(i=0;i<uniq_count;i++)
{
printf("%s\t\t%d\n",uniq_words[i],freq[i]);
}
getch();
}
Output
Enter the string :as a wood chuck would if a wood chuck could chuck wood
Word Frequency
as 1
a 2
wood 3
chuck 3
would 1
if 1
could 1