我们知道,一般编写程序时都要画出流程图,按照流程图结构来编程,如果编写一个比较繁琐,容易思维混乱的程序时,我们可以利用有限状态机模型画出一个状态转移图,这样便可以利用画出的逻辑图来编写程序,简洁且不易出错。
那什么是有限状态机是什么意思呢?百度百科上这样解释:
有限状态机,(英语:Finite-state machine, FSM),又称有限状态自动机,简称状态机,是表示有限个状态以及在这些状态之间的转移和动作等行为的数学模型。
#include <stdio.h> int main(int argc, char *argv[]) { char flag = 0; int ch; while((ch = getchar()) != EOF) { switch(flag) { case 0: if(ch == ' ') flag = 1; putchar(ch); break; case 1: if(ch == ' ') continue; flag = 0; putchar(ch); break; default: break; } } return 0; }
fs@ubuntu:~/qiang/char1$ gcc -o test test.c fs@ubuntu:~/qiang/char1$ ./test H el lo H el lo
#include <stdio.h> int main(int argc, char *argv[]) { char flag = 0; int ch; while((ch = getchar()) != EOF){ switch(flag){ case 0: if(ch == ' ') flag = 1; if(ch == '"') flag = 2; putchar(ch); break; case 1: if(ch != ' '){ flag = 0; if(ch == '"') flag = 2; putchar(ch); } break; case 2: if(ch == '"') flag = 0; if(ch == '\"') ch = '"'; putchar(ch); break; default: printf("error!\n"); break; } } return 0; }
fs@ubuntu:~/qiang/char1$ ./char3 H el "wor ld" lo H el "wor ld" lo
/*****This is a program!*****/ #include <stdio.h> int main() { printf("Hello world!\n");//Hello world! }
#include <stdio.h> int main(void) { char flag = 0; char ch; while((ch = getchar()) != EOF) { switch(flag) { case 0: if(ch == '/') flag = 1; else putchar(ch); break; case 1: if(ch == '/'){ flag = 2; } else{ putchar('/'); putchar(ch); } break; case 2: if(ch == '\n') { flag = 0; putchar(ch); } break; default: break; } } }
fs@ubuntu:~/qiang/char1$ ./quzhushi1 < test.c >result.c
/*****This is a program!*****/ #include <stdio.h> int main() { printf("Hello world!\n"); }
/*****This is a program!*****/ #include <stdio.h> int main() { printf("Hello world!\n");//Hello world! }
#include <stdio.h> int main() { char ch; int flag = 0; while((ch = getchar()) != EOF) { switch(flag) { case 0: if(ch == '/') flag = 1; else putchar(ch); break; case 1: if(ch == '/') flag = 2; else if(ch == '*') flag = 3; else { flag = 0; putchar('/'); putchar(ch); } break; case 2: if(ch == '\n') { putchar(ch); flag = 0; } break; case 3: if(ch == '*') flag = 4; break; case 4: if(ch == '/') flag = 0; else flag = 3; break; } } }
fs@ubuntu:~/qiang/char1$ ./quzhushi < test.c >result.c
#include <stdio.h> int main() { printf("Hello world!\n"); }