题目大意: 输入一组字符串,只由小写字母和空格组成,让你统计不同单词的个数,注意是不同的个数 。
特殊数据 1,直接输入一个换行,应该输出0
2,连续输出多个空格 在加上一个换行 应该输出0
3,输入 “ni shi wo wo de de de de hao hao ”应该输出5
6, 输入” 空格空格ni空格空格shi “ 应该输出2
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2072
#include<stdio.h>
#include<string.h>
int main()
{
char c, temp[100];
char str[10000][100];
int i;
while( (c = getchar())!= '#'){ //判断要不要结束
int ans = 0;
int k = 0;
int s = 0;
if(c == '\n'){ //判断第一个输入的是不是换行
printf("0\n");
continue;
}
while(1){
temp[k++] = c; //因为我是先将字符加进字符数组里面,看下面也带有****
if(temp[0] == ' '){ ///这处是判断是不是连续的几个空格输入, 如果是,就将k 重新赋值为0
k = 0;
// memset(temp, 0, sizeof(temp));
}
else if(temp[0] == '\n'){ //判断是不是为换行符
break;
}
else if( c == ' '){ //如果temp【0】 不是空格,即temp数组里面已经有字符了
temp[k-1] = '\0'; //所以这处是要将temp[k-1] =‘\0’, 作为一个单词的结束 ****
for(i = 0; i <s; i ++) //判断 是不是前面已经出现了
if(strcmp(str[i], temp) == 0)
break;
if(i == s){ //如果没有出现, 添加进数组里面, ans加1
strcpy(str[s++], temp);
++ans;
}
k = 0;
}
else if( c == '\n'){ //temp【0】 不是换行, 即temp数组里面已经有字符了, 也要判断一下
temp[k-1] = '\0'; //原理同上
// printf("%s", temp);
for(i = 0; i <s; i ++)
if(strcmp(str[i], temp) == 0)
break;
if(i == s)
strcpy(str[s++], temp),
k = 0,
++ans;
break;
}
c = getchar();
}
printf("%d\n", ans);
}
return 0;
}
代码(有解释):