Description
写一个函数实现:输入一行字符,以空格分割单词,回车结束输入,输出单词的个数
输入样例
There are many students and many trees!
输出样例
7
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[80];
int i;
int num=0;
gets(a);
for(i = 0; a[i] != '\0'; i++)
{
if ((a[i] >='a' && a[i] <='z') || (a[i] >='A' && a[i] <='Z'))
{
do
{
i++;
}while((a[i] >='a' && a[i] <='z') || (a[i] >='A' && a[i] <='Z'));
num++;
}
}
printf("%d\n",num);
return 0;
}
另一种:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s[80] = "";
int flag = 0, cnt = 0, i;
gets(s);
for(i = 0; s[i] != '\0'; i++)
{
if((s[i]>='a' && s[i]<='z') ||
(s[i]>='A' && s[i]<='Z'))
{
flag = 1;
}
else
{
if(flag == 1)
cnt++;
flag = 0;
}
}
if(flag == 1)
printf("%d",cnt+1);
else
printf("%d",cnt);
return 0;
}
标程
#include<stdio.h>
main()
{ int num=0,word=0;
char c;
while((c=getchar())!='\n')
{
if(!(c>='a'&&c<='z'||c>='A'&&c<='Z'))word=0;
else if(word==0)
{ word=1;
num++;
}
}
printf("%d",num);
}