c++从键盘输入一段字符串,统计其中字符的频率,并按照从大到小顺序输出
时间: 2024-09-27 12:08:05 浏览: 43
在 C++ 中,你可以通过以下步骤来实现这个功能:
1. 首先,你需要包含必要的头文件,如 `<iostream>`、`<string>` 和 `map`,`map` 可以存储键值对,方便查找和排序。
```cpp
#include <iostream>
#include <string>
#include <map>
#include <algorithm> // 使用 sort 函数
```
2. 创建一个函数来读取用户输入的字符串,并统计每个字符及其出现次数。
```cpp
std::string inputString;
std::cin >> inputString;
// 使用 map 存储字符频率
std::map<char, int> charCount;
for (char c : inputString) {
if (isalpha(c)) { // 过滤非字母字符
charCount[c]++;
}
}
```
3. 对字符频率进行排序。这里我们选择从大到小排序,所以需要自定义一个比较函数作为 `sort` 的第三个参数。
```cpp
bool compare(const std::pair<char, int>& a, const std::pair<char, int>& b) {
return a.second > b.second;
}
// 使用 sort 按照计数值降序排列字符
std::vector<std::pair<char, int>> sortedChars(charCount.begin(), charCount.end());
std::sort(sortedChars.begin(), sortedChars.end(), compare);
```
4. 输出排序后的结果。
```cpp
std::cout << "字符频率(按从大到小排序):" << std::endl;
for (const auto& pair : sortedChars) {
std::cout << '\'' << pair.first << "\': " << pair.second << std::endl;
}
```
完整代码示例:
```cpp
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
bool compare(const std::pair<char, int>& a, const std::pair<char, int>& b) {
return a.second > b.second;
}
int main() {
std::string inputString;
std::cin >> inputString;
std::map<char, int> charCount;
for (char c : inputString) {
if (isalpha(c)) {
charCount[c]++;
}
}
std::vector<std::pair<char, int>> sortedChars(charCount.begin(), charCount.end());
std::sort(sortedChars.begin(), sortedChars.end(), compare);
std::cout << "字符频率(按从大到小排序):" << std::endl;
for (const auto& pair : sortedChars) {
std::cout << '\'' << pair.first << "\': " << pair.second << std::endl;
}
return 0;
}
```
阅读全文
相关推荐


















