练习11.4:扩展你的程序,忽略大小写和标点。例如,"example."、"example,"和"Example"应该递增相同的计数器。
#include <stdio.h>
#include <iostream>
using namespace std;
#include <string>
#include <map>
int main(int argc,char *argv[])
{
map<string, size_t> word_count;
string word;
while (cin >> word)
{
for (auto &c : word)
{
c = tolower(c); //大写转小写
}
if (ispunct(*--word.end())) //查看末尾位置是否是标点
{
//word = word.substr(0, word.size() - 1); //将末尾位置标点删除
word.erase(word.end() - 1);
}
++word_count[word]; //递增计数器
}
for (const auto &w : word_count) //遍历
{
cout << w.first << " " << "occurs" << " " << w.second
<< ((w.second > 1) ? "times" : "time") << endl;
}
return 0;
}
本文介绍了一个使用C++编写的简单程序,该程序能够读取标准输入中的文本,并统计每个单词出现的次数,同时忽略了大小写和标点符号的影响。
606

被折叠的 条评论
为什么被折叠?



