/*
输入一行由字母和空格组成的字符串(不超过1024个字符),统计该字符串中单词的个数。设单词之间用一个或多个空格分隔,但第一个单词之前和最后一个单词之后可能没有空格。
*/
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
int HowManyWord(char *);
int main()
{
int const N=1024;
char str[N];
printf("Please input a string:");
fgets(str,sizeof(str),stdin);//fgets函数读入的字符串在串结束符前有\n
//str[strlen(str)-1]='\0';
printf("There are %d words\n",HowManyWord(str));
system("pause");
return 0;
}
int HowManyWord(char *string)
{
int num=1,flag;
while(*string !='\0')
{
while(isspace(*string++));
num++;
if(*string=='\0') //这里判断是否是文本行尾,即最后一个单词后有几个空格,然后是串结束符,若是则进行记录,统计的单词个数多了1
flag=1;
while(isalpha(*string++));
}
return flag?num-1:num;
}
计算以空格为分隔符的字符串中数字的个数
最新推荐文章于 2022-03-19 12:28:49 发布