去除输入字符中的多余星号

1、问题描述

    将标准输入流的字符中的多余'*'号过滤,并显示到标准输出。比如输入***hell*o*wor******ld***!!*###,显示*hell*o*wor*ld*!!*###。

2、有限状态机模型

       其中s1、s2是状态,a1、a2是状态机的转换函数,c1、c2转换的条件,表示非'*'字符还是'*'字符。

3、实现源码

/*
 *  Copyright:
 *  Author: snail
 *	Date: 2018-07-18
 *  Description:去除字符串的多余*号
 */

#include <iostream>
using namespace std;

typedef int State;
typedef struct
{
	int index;
	char info;
}Condition;

#define STATES 2
#define STATE_1 0
#define STATE_2 1

#define CONDITIONS 2
#define CONDITION_1 0
#define CONDITION_2 1

typedef void(*ActionType)(State state, Condition condition);

typedef struct
{
	State next;
	ActionType action;
} Trasition, *pTrasition;

void action_1(State state, Condition condition)
{
	cout << condition.info;
}

void action_2(State state, Condition condition)
{
	// nothing to do
}

// (s1, c1, s1, a1)
Trasition t1 = {
	STATE_1,
	action_1
};

// (s1, c2, s2, a1)
Trasition t2 = {
	STATE_2,
	action_1
};

// (s2, c1, s1, a1)
Trasition t3 = {
	STATE_1,
	action_1
};

// (s2, c2, s2, a2)
Trasition t4 = {
	STATE_2,
	action_2
};

pTrasition transition_table[STATES][CONDITIONS] = {
	/*      c1,  c2*/
	/* s1 */&t1, &t2,
	/* s2 */&t3, &t4,
};

typedef struct
{
	State current;
} StateMachine, *pStateMachine;

State step(pStateMachine machine, Condition condition)
{
	pTrasition t = transition_table[machine->current][condition.index];
	(*(t->action))(machine->current, condition);
	machine->current = t->next;
	return machine->current;
}

int main()
{	
	State state = STATE_1;
	Condition condition = { 0, EOF };
	pStateMachine machine = new StateMachine();
	machine->current = state;

	int ch = EOF;
	while ((ch = cin.get()) != EOF)
	{
		if (ch != '*')
		{
			condition.index = CONDITION_1;
		}
		else
		{
			condition.index = CONDITION_2;
		}
		condition.info = ch;
		step(machine, condition);
	}
}

4、实验结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值