C++ primer 第五版 中文版 练习 11.4
题目:扩展你的程序,忽略大小写和标点。例如,"example.","example,"和"Example",应该递增相同的计数器。
答:
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
map<string, size_t> word_count;
string word;
string hulue = ",."; //忽略 ","和"."
while (cin >> word)
{
//删除","和"."
auto iter=word.find_first_of(hulue);
if (iter!=string::npos)
word.erase(iter);
//全部转换为小写字母
for (auto &s : word)
s = tolower(s);
//统计个数
++word_count[word];
}
for (const auto &w : word_count)
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;
return 0;
}