英文单词个数的统计
程序员文章站
2024-02-23 23:34:54
...
//2018 /4/21
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define init_word 0
#define in_word 1
#define out_word 2
#define end_word 3
int count_word(char *ch);
int main()
{
char ch[100] = {"small big pig jkd"};
int num = count_word(ch);
printf("-------------num = %d-----------------\n",num);
return 0;
}
int count_word(char *ch)
{
int num = 0;
int tag = init_word;
for (int i = 0;ch[i] !='\0';++i)
{
switch(tag)
{
case init_word:
if(isalpha(ch[i]))
{
tag = in_word;
}
else
{
tag = out_word;
}
break;
case in_word:
if(!isalpha(ch[i]))
{
tag = out_word;
num = num + 1;
}
break;
case out_word:
if(isalpha(ch[i]))
{
tag = in_word;
}
break;
case end_word:break;
}
}
if(tag == in_word)
{
num = num +1;//为什么要加这一句(因为不加这一句会少统计一个单词,原因出在for循环(ch[i]上),最后一个单词直接跳出循 //环没有统计上)
}
return num;
}