zoukankan      html  css  js  c++  java
  • C++语言,统计一篇英文文章中的单词数(用正则表达式实现)

    下面的例子展示了如何在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 += '
    ';
                }
                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;
    }
  • 相关阅读:
    mysql 单表查询
    socket 阻塞,同步、I/O模型
    I/O复用
    send函数和recv函数
    linux网络编程、系统编程
    TCP三次握手、四次挥手
    支持中文的PHP按字符串长度分割成数组代码
    php json_encode 处理中文
    php base64各种上传
    本地创建分支
  • 原文地址:https://www.cnblogs.com/kingshow123/p/charcount.html
Copyright © 2011-2022 走看看