求助:要求统计一行字符串中某单词出现的次数,要求字符串从键盘输入,并调用函数完成统计。如输入how are you ,统计are的次数,结果为1

zirandeai 2008-06-11 01:08:26
请高手帮忙,程序中请尽量使用简单语句,本人初学者,谢谢
...全文
1546 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
luxiaoxun 2008-06-16
  • 打赏
  • 举报
回复
#include "stdio.h"
#include "string.h"
int main()
{
char ch;
char s[1000];
char word[1000][20]; /* 最多存1000个不同单词,每个单词在20个字符内。 */
int count_word[1000]={0}; /* 每个单词对应个数 */
int i=0,j=0,k=0,flag=2,total=0;
double percent; /* 每个单词出现频率 */
gets(s);
strcat(s,".");
char *p=s;
while(*p)
{
ch=*p;
if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z')
{
if(ch>='A'&&ch<='Z') ch+=32;
flag=0;
word[i][j]=ch;
j++;
}
else flag++;
if(flag==1)
{
total++;
word[i][j]='\0';
count_word[i]++;
for(k=0;k<i;k++)
if(strcmp(word[i],word[k])==0)
{
count_word[k]++;
count_word[i]=0;
i--; break;
}
i++;
j=0;
}
p++;
}

printf("result----------------------------------------");
for(k=0;k<i;k++)
{
printf("\n%-20s",word[k]);
printf("%-10d",count_word[k]);
percent=100.0*count_word[k]/total;
printf("%.2f",percent);
}
printf("\n\nThis text has %d word(s).",total);
printf("\nAnd here has %d different word(s).",i);
return 0;
}
能用map就非常简单了
mwx285 2008-06-16
  • 打赏
  • 举报
回复
学习了,strstr不错,又长见识类
stars_eyes 2008-06-11
  • 打赏
  • 举报
回复
没注意要求在题目上,重来

#include"stdio.h"
void main()
{
char str1[200],str2[20];
void count(char str1[],char str2[]);
gets(str1);
gets(str2);
count(str1,str2);
}

void count(char str1[],char str2[])
{
int i,j,num=0;
for(i=0,j=0;str1[i]!='\0';i++)
{
while(str1[i]==str2[j])
{
if(str1[i]=='\0')
{
num++;
break;
}
i++;
j++;
}
if(str1[i]==' '&&str2[j]=='\0')
num++;
j=0;
}
printf("%d\n",num);
}
stars_eyes 2008-06-11
  • 打赏
  • 举报
回复
#include"stdio.h"
void main()
{
char str1[200],str2[20];
gets(str1);
gets(str2);
int i,j,num=0;
for(i=0,j=0;str1[i]!='\0';i++)
{
while(str1[i]==str2[j])
{
if(str1[i]=='\0')
{
num++;
break;
}
i++;
j++;
}
if(str1[i]==' '&&str2[j]=='\0')
num++;
j=0;
}
printf("%d\n",num);
}
K行天下 2008-06-11
  • 打赏
  • 举报
回复
随便写一个,统计输入的第一个单词出现的次数:
如果输入:

how are you howhowhow
how出现的次数是:4


#include <stdio.h>
#include <string.h>

int wordStatistic(char* line, char* word);
int main()
{
char s[1024];
char l[20];
char *p = s, *q = l;
int count;
while( (*q++ = *p++ = getchar()) != '\n')
{
if(*(q-1) == ' ')
*(q-1) = '\0';
}
*p = '\0';

count = wordStatistic(s,l);
printf("%s出现的次数是:%d\n",l,count);
getchar();
return 0;
}
int wordStatistic(char* line, char* word)
{
int count = 0;
while ( line = strstr(line, word) )
{
line++;
count++;
}
return count;
}



blh 2008-06-11
  • 打赏
  • 举报
回复
strstr

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧