gpt4 book ai didi

c - 字符串中单词的频率

转载 作者:太空宇宙 更新时间:2023-11-04 04:13:57 24 4
gpt4 key购买 nike

好吧,我正在解决我的作业,在这个特定的程序中,单词“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 的频率,即使它在字符串中出现了两次。 Check the link for the output on the terminal?

最佳答案

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

关于c - 字符串中单词的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53970726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com