How to count different words from a text on C?

Saturday, May 3, 2014

I wrote this code but it looks so bad. This function prints how much is repeated each word. Is there another way to do the same function simple and easy to understand?



int diffrentwords(FILE *myinput){
int i,j,words[40],difwords=0;
char text[40][40];
char a;

rewind(myinput);
for(i=0;i<40;i++){
words[i]=0;
for(j=0;j<40;j++)
text[i][j]=' ';
}
for (i=0;i<40;i++){
if(feof(myinput))
break;
for(j=0;j<40;j++){
a=fgetc(myinput);
if(a!=' ')
text[i][j]=a;
else{
text[i][j]='\0';
break;
}
}
}
text[i][0]='\0';
i=0;

for(i=0;text[i][0]!='\0';i++)
for(j=i+1;text[j][0]!='\0';j++)
if(text[j][0]!=' ' && !(strcmp(text[i],text[j]))){
words[i]++;
text[j][0]=' ';
}
for(i=0;text[i][0]!='\0';i++)
if(text[i][0]!=' '){
printf("%s \t %d\n",text[i],words[i]+1);
difwords++;
}
printf("\n");
return difwords;


}







http://ift.tt/1oeuxVF