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、实验结果