代码改变世界

C++语言,统计一篇英文文章中的单词数(用正则表达式实现)

2013-11-05 16:18  kingshow  阅读(1786)  评论(0编辑  收藏  举报

下面的例子展示了如何在C++11中,利用regex_search()统计一篇英文文章中的单词数:

#include <iostream>
#include <regex>
#include <string>
#include <fstream>
using namespace std;
// 统计单词数
int countword(string& str)
{       try
        {
            int n = 0;
            smatch m; // 保存匹配结果的match_result
            // 匹配单词的正则表达式,
            // 包含了大小写英文字母,连字符,括号,引号
            // 这个正则表达式还不完善,可以继续改进
            regex ex("\\b[a-zA-Z-()\"]*\\b");
            // 用regex_search()在文章中进行匹配,查找单词
            while(regex_search(str,m,ex))
            {
                ++n;  // 找到,总数加1
                cout<<m[0]<<endl; // 输出找到的单词
                str = m.suffix().str(); // 移动到下一个位置
            }
            return n;
        }
        catch (regex_error e)
        {
            cout<<e.what()<<endl;
        }
}
// 读取文件内容
bool readfile(const string name,string& str)
{
    ifstream in(name);
    if(in.is_open())
    {
        char line[512] = "";
        while(true)
        {
            in.getline(line,512);
            str += line;
            if(in.good())
            {
                str += '\n';
            }
            else
            {
                break;
            }
        }
        return true;
    }
    else
    {
        return false;
    }
}
int main(int argc,char* argv[])
{
    if(2 != argc)
    {
        cout<<"argument error. eg. count.exe demo.txt"<<endl;
    }
    string str("");
    if(readfile(argv[1],str))
    {
        int n = countword(str);
        cout<<"there are "<<n<<" words in "<<argv[1]<<endl;
    }
    return 0;
}