码迷,mamicode.com
首页 > 其他好文 > 详细

一个简单的有穷状态机-单词数统计程序

时间:2014-09-26 00:53:08      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   使用   ar   for   sp   

 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::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             else
32             {
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                 //状态发生转换
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         }//switch
53     }//for
54     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 }

使用状态机的直接好处就是让问题分析简单化。

一个简单的有穷状态机-单词数统计程序

标签:style   blog   color   io   os   使用   ar   for   sp   

原文地址:http://www.cnblogs.com/zigzagh/p/3993875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!