使用std::map或std::unordered_map统计字符频率,前者有序适合按序输出,后者高效适合大数据;可结合isalpha和tolower实现字母忽略大小写统计。

在C++中统计字符串中每个字符的出现频率,常用的方法是使用std::map或std::unordered_map来存储字符和对应的频次。下面介绍几种实用且高效的实现方式。
std::map会自动按键(这里是字符)排序,适合需要按字母顺序输出结果的场景。
#include <iostream>
#include <map>
#include <string>
int main() {
std::string str = "hello world";
std::map<char, int> freq;
for (char c : str) {
freq[c]++;
}
for (const auto& pair : freq) {
std::cout << "'" << pair.first << "': " << pair.second << std::endl;
}
return 0;
}
这段代码遍历字符串中的每个字符,并在map中累加其出现次数。输出结果按字符ASCII码排序。
如果不需要排序,std::unordered_map具有更快的平均查找和插入速度(O(1)),更适合大数据量处理。
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::string str = "programming";
std::unordered_map<char, int> freq;
for (char c : str) {
freq[c]++;
}
for (const auto& pair : freq) {
std::cout << "'" << pair.first << "': " << pair.second << std::endl;
}
return 0;
}
与map相比,unordered_map不会排序输出,但性能更优。
有时我们只关心英文字母,并希望将大写和小写视为同一字符。
#include <iostream>
#include <unordered_map>
#include <string>
#include <cctype>
int main() {
std::string str = "Hello World!";
std::unordered_map<char, int> freq;
for (char c : str) {
if (std::isalpha(c)) {
freq[std::tolower(c)]++;
}
}
for (const auto& pair : freq) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
这里用std::isalpha判断是否为字母,std::tolower统一转为小写后再统计。
基本上就这些。根据实际需求选择合适的数据结构和过滤条件,就能高效完成字符串字符频率统计任务。不复杂但容易忽略细节,比如空格、标点或大小写处理。
以上就是c++++中如何统计字符串字符频率_c++字符串字符频率统计方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号