Problem A: 零起点学算法113——统计单词个数
Time Limit: 1 Sec Memory Limit: 64 MB
Submit: 3344 Solved: 1131
Description
输入一行字符(少于80个字符),以回车结束,统计其中单词的个数。各单词之间用空格分隔,空格数可以是多个。
Input
多组测试,输入一字符串,以回车结束。
Output
输出该字符串中单词的个数
Sample Input
This is a c program.
Sample Output
5
HINT
这道题后台数据其实不是那么严谨 所以是可以卡bug过的
bug 代码:
#include<stdio.h>
#include<string.h>
char
str[100];
int
main(
void
)
{
int
i,j;
while
(
gets
(str)!=NULL)
{
int
count=0;
for
(i=0;i<
strlen
(str);i++)
{
if
(str[i]!=
' '
)
{
for
(j=i;j<
strlen
(str);j++)
{
if
(str[j]==
' '
)
{
count++;i=j;
break
;
}
}
}
}
printf
(
"%d\n"
,count+1);
memset
(str,
'/0'
,
sizeof
(str));
}
return
0;
}
问题在于这里如果最后一个单词继续打空格。就会出事。然后题目后台数据没有这类。所以能过
所以我们换种思路:str【0】是字母的时候直接count++;然后以后只要第一个是空格接下来是字母就count++。这样做就不用考虑最后单词的问题了。
代码如下:
#include<stdio.h>
#include<string.h>
char str[100];
int main(void)
{
int i,j;
while(gets(str)!=NULL)
{
int count=0;
if(str[0]>='a'&&str[0]<='z'||str[0]>='A'&&str[0]<='Z')
count++;
for(i=1;i<strlen(str);i++)
{
if(str[i]==' '&&(str[i+1]>='a'&&str[i+1]<='z'||str[i+1]>='A'&&str[i+1]<='Z'))
count++;
}
printf("%d\n",count);memset(str,'/0',sizeof(str));
}
return 0;
}
这个鲁棒性更强