c - 字符串中单词的频率
问题描述
好吧,我正在解决我的作业,在这个特定的程序中,单词“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 的频率,即使它在字符串中出现两次。 检查终端上输出的链接?
解决方案
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
推荐阅读
- batch-file - if\else 在网络位置上无法按预期工作
- reactjs - 导航到屏幕或组件时刷新屏幕或组件
- python - 如何使用 wrapt.decorator 适配器更改未绑定方法的签名?
- reactjs - 反应本机相机 - 如何?
- java - 在java中将数据字节传递给FileReader
- gradle - 我可以在 Android Gradle 项目中将 lint-result.xml 上传到 SonarQube 吗?
- c++ - 查找字符在两个索引之间出现的次数
- c# - 用于创建表的继承映射
- c# - 如何使双值的 C++ 和 C# 中的结果相同
- python-3.x - 嵌套 if else 语句未在 Python 中执行