状态机解析字符串
#include <stdio.h> #include <stdlib.h> #ifdef DEBUG #define PRINT printf #else #define PRINT #endif typedef void (*ACT)(void); static char buf[64]; static int j ; static char c; int find_type(char key) { if(key >= 'a' && key <= 'z') return 1; // 小写字符 if(key >= 'A' && key <= 'Z') return 1; // 大写字符 if(key >= '0' && key <= '9') return 2; // 数字 if(key == '\0') return 3; // 结束 return 0; // 其他 } void act_body(void) { buf[j++] = c; } void act_tail(void) { PRINT("word tail found\n"); buf[j] = '\0'; printf("word is %s \n", buf); } void act_tail2(void) { PRINT("word tail found\n"); buf[j] = '\0'; printf("number is %s \n", buf); } void act_head(void) { PRINT("word head found!\n"); j = 0; buf[j++] = c; } void act_null(void) { return; } void act_end_begin() { act_tail(); act_head(); } void act_end2_begin() { act_tail2(); act_head(); } ACT acts[3][4] = { act_null, act_head,act_head, act_null, act_tail, act_body, act_end_begin, act_tail, act_tail2, act_end2_begin, act_body, act_tail2, }; int state_trans[3][4] = { 0, 1, 2, -1, 0, 1, 2, -1, 0, 1, 2, -1, }; int main(void) { int state = 0; int i = 0; char *str = "hello, 123, hello worlda 567"; printf("%s\n", str); while(state != -1) { int input; c = str[i]; input = find_type(c); acts[state][input](); state = state_trans[state][input]; i++; } return 0; } #if 0 switch(state) { case 0://" " switch (input) { case 0:// " " state = 0; act_null(); break; case 1:// "a" state = 1; act_head(); break; case 2:// "\0" state = -1; act_null(); break; } break; case 1://"a" switch(input) { case 0:// " " state = 0; act_tail(); break; case 1:// "a" state = 1; act_body(); break; case 2:// "\0" state = -1; act_tail(); break; } break; default : break; } i++; } printf("\n"); return 0; } #endif