作者: Turbo时间限制: 1S章节: 字符串
问题描述 :
编写一个程序,输入一个句子,然后统计出这个句子当中不同的单词个数。例如:对于句子“one little two little three little boys”,总共有5个不同的单词:one, little, two, three, boys。
说明:(1)由于句子当中包含有空格,所以应该用gets函数来输入这个句子;(2)输入的句子当中只包含英文字符和空格,单词之间用一个空格隔开;(3)不用考虑单词的大小写,假设输入的都是小写字符;(4)句子长度不超过100个字符。
输入说明 :
输入只有一行,即一个英文句子。
输出说明 :
输出只有一行,是一个整数,表示句子中不同单词的个数。
输入范例 :
one little two little three little boys
输出范例 :
5
代码及思想:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char ss[50][50];//用来存放只出现过一次的单词
int main()
{
char s[100];
int i=0,count=0,flag,tag;
gets(s);
int len=strlen(s);
// printf("len=%d\n",len);
while(i<len)//通过遍历来把单词提取到temp中
{
int j=0;//j控制temp的下标
char temp[50];//temp保存当前的检测到的单词
for(;(s[i]!=' ')&&(s[i]!='\0');i++)//遇到空格或者结束标志时结束一次对单词的检测
{
temp[j++]=s[i];
}
i++;//因为当前的i在一个空格的位置,所以要i++跳到下一个单词的第一位
temp[j]='\0';
tag=1;//tag用来标志temp是否在ss中出现过
for(int k=0;k<count;k++)//通过循环来检测,出现过则将tag置0,直接退出检测循环,如果与ss中所有单词都不同则tag还是1,将temp中的单词填入ss,count+1;
{
if(strcmp(temp,ss[k])==0)
{
tag=0;
break;
}
}
if(tag==1)
{
// printf("temp=%s\n",temp);
strcpy(ss[count++],temp);
}
}
printf("%d\n",count);
return 0;
}