switch实现状态机
实现条件:只考虑了多个空格,暂未考虑其他单词合法性等问题,注重思路即可
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
//枚举状态0开始,1在单词中,2在单词外,3结束
enum status
{
BEGIN = 0,
INWORD = 1,
OUTWORD = 2
};
int main()
{
char str[] = {
" hello world time is life ohhhh"};
//默认状态开始
enum status status = BEGIN;
int count = 0; //单词个数
for(int i = 0; i < strlen(str); i++)
{
switch(status)
{
case BEGIN:
if(isalpha(str[i]))
{
status = INWORD;
}
else
{
status = OUTWORD;
}
break;
case INWORD:
if(!isalpha(str[i]))
{
status = OUTWORD;
count++;
}
break;
case OUTWORD:
if(isalpha(str[i]))
{
status = INWORD;
}
break;
}
}
if(status == INWORD)
count++;
printf("str:\"%s\" of words = %d\n", str, count);
}
结果: