输入一串文本,统计其中出现单词的个数,并按字典序输出。c++
时间: 2024-05-09 11:15:25 浏览: 6
以下是 C++ 的代码实现:
```cpp
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
int main() {
string text;
getline(cin, text);
map<string, int> wordCount;
// 将所有字符转为小写,便于统计单词
transform(text.begin(), text.end(), text.begin(), ::tolower);
// 统计单词数量
string word = "";
for (char c : text) {
if (isalpha(c)) {
word += c;
} else {
if (word != "") {
wordCount[word]++;
word = "";
}
}
}
if (word != "") {
wordCount[word]++;
}
// 按字典序输出单词及其数量
for (auto it = wordCount.begin(); it != wordCount.end(); ++it) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
```
输入一串文本,程序会统计其中出现的单词数量,然后按字典序输出。其中,使用了 STL 中的 map 容器来存储每个单词的出现次数。也可以使用 unordered_map 容器,但是输出顺序可能会有所不同。