不用正则表达式统计文本中字符(包括标点)出现的次数

如题,其实根本不用正则表达式。

#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;

int main(){

    ifstream is("/Users/.../test2.txt");
    if (!is) {
        cerr << "File cannot be opened!\n";
        exit(EXIT_FAILURE);
    }

    map<char,int> cMap;

    char word;
    while ((word = is.get()) != EOF) {
        if (word != '\n' && word != ' ')    //换行符与空格不统计
        cMap[word]++;
    }
    cout << "Finish reading...\n";

    map<char,int>::const_iterator it;
    for (it = cMap.begin();it != cMap.end();it++)
        cout << it->first << " : " << it->second << "次" << endl;

    return 0;
}

标点符号也能匹配,更通用。

猜你喜欢

转载自blog.csdn.net/qq_32925781/article/details/79568282