A Simple Finite State Machine-Word Count statistics program

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.