利用状态机求字符串中单词的个数(字符串中仅包含字母,空格,数字),字母的个数,数字的个数和空格的个数

#include<stdio.h>
#include<stdlib.h>

#define MAX 100
#define BOOL int

#define init_state 1
#define space_state 2
#define word_state 3
#define number_state 4
int main(void)
{
//	BOOL init_state=1,space_state=2,word_state=3;
	BOOL state=init_state;
	int wordnum=0;//统计单词的个数
	int spacenum=0;
	int characnum=0;
	int numbernum=0;
	char *str=(char *)malloc(sizeof(char)*100);
	char *strcopy;
	printf("enter the string str:\n");
	gets(str);
	strcopy=str;
	while(*str != '\0')  //A~Z  --> a~z
	{
		if(*str >='A' && *str <='Z')
		{
			*str=*str+'a'-'A';
		}
		str++;
	}
	str=strcopy;
	while(*str !='\0')
	{   
		switch(state)
		{
		case init_state:
			{
				if(*str == ' ')  
				{
					state=space_state;
					spacenum++;
				}
				else if(*str >='a' && *str<='z')
				{
					state=word_state;
					wordnum++;
					characnum++;	    					
				}
				else
				{
					state=number_state;
					numbernum++;
				}
				break;
			}
		case space_state:
			{
				if(*str >='a' && *str <='z')
				{
					state=word_state;
					wordnum++;
					characnum++;
				}
				else if(*str >='0' && *str<='9')
				{
					state=number_state;
					numbernum++;
				}
				else
					spacenum++;
				
				break;
			}
		case word_state:
			{
				if(*str ==' ')
				{
					state=space_state;
					spacenum++;
				}
				else if(*str >='0' && *str <= '9')
				{
					state=number_state;
					numbernum++;
				}
				else
				{
					characnum++;	
				}
				break;
			}

		case number_state:
			{
				if(*str ==' ')
				{
					state=space_state;
					spacenum++;
				}
				else if(*str >='a' && *str<='z')
				{
					state=word_state;
					wordnum++;
					characnum++;
				}
				else
				{
					numbernum++;	
				}
				break;
			
			}
		}
       str++;
	}

	printf("the word' number in this string is %d\n",wordnum);
    printf("the character' number in this string is %d\n",characnum);
	printf("the space' number in this string is %d\n",spacenum);
	printf("the number' number in this string is %d\n",numbernum);
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值