一.题目描述
Description
读入一篇英文文章,基于STL中的容器和算法(建议包含<map>、<algorithm>、<string>和<sstream>),删除所有标点符号,主要包括英文逗号“,”、句号“.”、分号“;”、感叹号“!”、问号“?”、双引号“"”和单引号“'”等,并将所有英文单词转化为小写,然后统计每个单词出现的频率并按“a-z”从小到大顺序输出结果。
二.输入与输出
Input
一段以exit为结束词的英文文本
Output
按从小到大顺序输出除标点外的小写单词及出现频率
Sample Input 1
Saying Goodbye to Cambridge AgainVery quietly I take my leave As quietly as I came here; Quietly I wave goodbye To the rosy clouds in the western sky.The golden willows by the riverside Are young brides in the setting sun; Their reflections on the shimmering waves Always linger in the depth of my heart.The floating heart growing in the sludge Sways leisurely under the water; In the gentle waves of Cambridge I would be a water plant!exit
Sample Output 1
a 1 again 1 always 1 are 1 as 2 be 1 brides 1 by 1 cambridge 2 came 1 clouds 1 depth 1 floating 1 gentle 1 golden 1 goodbye 2 growing 1 heart 2 here 1 i 4 in 5 leave 1 leisurely 1 linger 1 my 2 of 2 on 1 plant 1 quietly 3 reflections 1 riverside 1 rosy 1 saying 1 setting 1 shimmering 1 sky 1 sludge 1 sun 1 sways 1 take 1 the 11 their 1 to 2 under 1 very 1 water 2 wave 1 waves 2 western 1 willows 1 would 1 young 1
Sample Input 2
Stray Birds"WHAT language is thine, O sea?" "The language of eternal question." "What language is thy answer, O sky?" "The language of 'eternal' silence."exit
Sample Output 2
answer 1 birds 1 eternal 2 is 2 language 4 o 2 of 2 question 1 sea 1 silence 1 sky 1 stray 1 the 2 thine 1 thy 1 what 2
三.代码
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <sstream>using namespace std;bool isPunctuation(char c) {return c == ',' || c == '.' || c == ';' || c == '!' || c == '?' || c == '"' || c == '\'';
}string removePunctuation(const string& word) {string cleanedWord;for (size_t i = 0; i < word.size(); ++i) {char c = word[i];if (!isPunctuation(c)) {cleanedWord += c;}}return cleanedWord;
}int main() {string line, word;map<string, int> wordCount;while (getline(cin, line) && line != "exit") {transform(line.begin(), line.end(), line.begin(), ::tolower);stringstream ss(line);while (ss >> word) {string cleanedWord = removePunctuation(word);if (!cleanedWord.empty()) {wordCount[cleanedWord]++;}}}for (map<string, int>::iterator it = wordCount.begin(); it != wordCount.end(); ++it) {cout << it->first << " " << it->second << endl;}return 0;
}