首页 > 解决方案 > 字符串中单词的频率

问题描述

好吧,我正在解决我的作业,在这个特定的程序中,单词“say”的输出显示为 1,即使它出现了两次。

//Start
    # include <stdio.h>
    # include <string.h>
    int main()
    {
     char Str[100]="Martha! Why did you say that name? Please! Stop! Why did 
                    you say that name?", Words[100][100], Temp[100];
  int i, j, k, n, Count;
  j=k=0;
  //Accepting input
  //gets(Str);
  Str[strlen(Str)]='\0';
  //Copying Each and every word into a 2-D Array from the string
   for(i=0;Str[i]!='\0';i++)
    {
     if(Str[i]==' ')
      {
       Words[j][k]='\0';
       k=0;
       j++;
      }
     else
      {
       Words[j][k++]=Str[i];
      }
    }
  Words[j][k] = '\0'; //Null character for last word
  n=j;
  //Sorting the array of words
  for(i=0;i<n-1;i++)
   {
    for(j=i+1;j<n;j++)
     {
      if(strcmp(Words[i], Words[j])>0)
       {
         strcpy(Temp, Words[i]);
         strcpy(Words[i], Words[j]);
         strcpy(Words[j], Temp);
       }
     }
   }
  printf("\n");
  //Displaying frequecncy of each word

   for(i=0;i<n;i+=Count) //Incrementing by count to process the next word
    {
     Count=1;
       {
        for(j=i+1;j<=n;j++)
          {
           if(strcmp(Words[i], Words[j])==0)
            {
             Count++;
            }
          }
       }
      printf("%s\t%d\n", Words[i], Count); //Count is used to display the frequecncy of each word
    }
  printf("\n");
  return 0;
}//End

这是输出:

Martha! 1

Please! 1

Stop!   1

Why     2

did     2

name?   2

**say     1**

that    2

you     2

如您所见,输出显示单词 'say' one 的频率,即使它在字符串中出现两次。 检查终端上输出的链接?

标签: cstring

解决方案


n未正确设置。

使用n = j;,从概念上讲,这应该n = j+1;用于n表示n单词而不是最后一个索引。

// n = j;
n = j+1;

如果没有上述更改,数组不会完全排序,因为n它被视为字数,但它太小了 1。

排序错误的数组是

Martha!, Please!, Stop!, Why, Why, did, did, name?, say, say, that, that, you, you, name?

不完整的排序,现在n用作最后一个索引,将频率计数弄乱了"name?"两次,但不是连续的顺序 - 因此跳过了第一个"say"

// for (j = i + 1; j <= n; j++) {
for (j = i + 1; j < n; j++) {

修复代码输出

Martha! 1
Please! 1
Stop!   1
Why 2
did 2
name?   2
say 2
that    2
you 2

推荐阅读