扩展你的程序,忽略大小写和标点。例如,"example."、"example,"和"Example"应该递增相同的计数器。
解题思路:自定义一个revise函数,在将word录入map之前,先对word进行逐字符解析,将原始word中的标点都去掉,然后所有字符转换为小写形式,形成一个新word,存入map。
#include <iostream>
#include <sstream>
#include <map>
#include <cctype>
#include <string>
using namespace std;
string revise(string& s)
{
string t;
for(auto it = s.cbegin(); it != s.cend(); ++it)
{
if(isalpha(*it))
t += tolower(*it);
}
return t;
}
int main()
{
string s = "Everything will be ok in the end, if it's not ok, it's not the End.";
map<string, int> m;
string word;
istringstream iss(s);
while(iss >> word)
++m[revise(word)];
for(auto e : m)
cout << e.first << " occurs " << e.second << " time" << (1 < e.second ? "s." : ".") << endl;
return 0;
}
执行结果:

本文介绍如何修改程序,通过`revise`函数处理字符串输入,忽略大小写并移除标点,确保相同单词无论形式如何变化,计数器均同步增加。
278

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



