21 统计单词
作者: Turbo时间限制: 1S章节: STL库
问题描述 :
实验目的:string、vector、类的综合应用。
实验内容:
从键盘输入一篇文章,统计其中单词出现的次数(不区分大小写),并输出出现次数排名第一的单词及其次数。注意:可能有多个单词并列第一,需要全部输出。输出时,如果有多个单词排名并列,则按其在文章中出现的先后顺序输出,先出现的先输出。
说明:为简单起见,单词的含义是空白字符分隔开的连续字符串。比如“I love China!”这句话包含三个单词,第三个单词是“China!”(包括其中的感叹号),再如“Hi !”,这句话包含两个单词,第二个单词仅为一个感叹号。
参考以下main函数:
int main()
{
vector<WordCount> vwc;
string str;
int i;
while(cin>>str)
{
str = ToLower(str);
CountWord(vwc, str);
}
DisplayResult(vwc);
return 0;
}
其中:
-
WordCount类:存储单词及其出现次数
-
ToLower函数:传入一个字符串,将其中大写英文字母转换为小写、其余字符保持不变,返回转换后的结果。
-
CountWord函数:传入一个vector和一个单词,在vector中查找该单词是否已存在(注意:vector中的元素为WordCount对象,该对象有一个属性为单词字符串),如果已存在,则将其出现次数加1,否则在vector中添加一个元素(WordCount对象),该元素存储这个新的单词及其出现次数(此时为1)。
-
DisplayResult函数:传入一个vector,输出其中出现次数最高的单词及其次数。
请实现以上定义的WordCount类及三个函数。
输入说明 :
输入一篇文章,其中包含可见字符及空白字符(可能有换行)。
输出说明 :
每个单词占一行,如果有n个单词,则输出n行,
每行首先输出单词(以小写字母形式输出),然后输出一个空格,再输出单词的出现次数。
单词输出的顺序按照在文章中出现的先后顺序。
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
class WordCount {
public:
string word;
int count;
int order;
WordCount(string w, int c, int o) : word(w), count(c), order(o) {}
};
string ToLower(string str) {
for (char& ch : str) {
ch = tolower(ch);
}
return str;
}
void CountWord(vector<WordCount>& vwc, string str, int order) {
for (auto& wc : vwc) {
if (wc.word == str) {
wc.count++;
return;
}
}
vwc.push_back(WordCount(str, 1, order));
}
void DisplayResult(vector<WordCount>& vwc) {
int max_count = 0;
vector<string> max_words;
for (auto& wc : vwc) {
if (wc.count > max_count) {
max_count = wc.count;
max_words.clear();
max_words.push_back(wc.word);
} else if (wc.count == max_count) {
max_words.push_back(wc.word);
}
}
for (auto& word : max_words) {
cout << word << " " << max_count << endl;
}
}
int main() {
vector<WordCount> vwc;
string str;
int order = 0;
while (cin >> str) {
str = ToLower(str);
order++;
CountWord(vwc, str, order);
}
DisplayResult(vwc);
return 0;
}