1 # include <iostream> 2 # include <cctype> 3 4 class wordcounter 5 {6 Enum class _ state 7 {8 state_init = 0, 9 state_in_word, 10 state_out_word, 11 }; 12 public: 13 static int count_words (const char * text); 14}; 15 16 int wordcounter: count_words (const char * Text) 17 {18 int counts = 0; 19 _ state = _ state: state_init; 20 const char * It = text; 21 22 for (; * It! = '\ 0'; it ++) 23 {24 switch (state) 25 {26 case wordcounter: _ state: state_init: 27 if (isalpha (* It )) 28 {29 State = _ state: state_in_word; 30} 31 else32 {33 State = _ state: state_out_word; 34} 35 break; 36 case wordcounter: _ state :: state_in_word: 37 If (! Isalpha (* It) 38 {39 State = _ state: state_out_word; 40 // status conversion 41 counts ++; 42} 43 break; 44 case wordcounter :: _ state: state_out_word: 45 if (isalpha (* It) 46 {47 State = _ state: state_in_word; 48} 49 break; 50 default: 51 break; 52} // switch53} // for54 if (_ state: state_in_word = State) 55 {56 counts ++; 57} 58 return counts; 59} 60 61 int main (INT argc, const char * argv []) 62 {63 using namespace STD; 64 char * TEXT = "My name is \ r \ n Percy !! This is BBC English "; 65 cout <text <'\ n' <wordcounter: count_words (text) <Endl; 66 getchar (); 67 return 0; 68}
The direct advantage of using a state machine is to simplify problem analysis.
A Simple Finite State Machine-Word Count statistics program