c++字符串中字符出现次数
作者:野牛程序员:2023-07-06 10:33:50 C++阅读 2944
要统计C++字符串中字符出现的次数,可以使用std::unordered_map(无序映射)来实现。以下是一个示例代码:
#include <iostream>
#include <unordered_map>
int main() {
std::string str = "Hello, World!";
std::unordered_map<char, int> charCounts;
// 统计字符出现次数
for (char c : str) {
// 如果字符已经在unordered_map中,则递增计数器
if (charCounts.find(c) != charCounts.end()) {
charCounts[c]++;
}
// 否则,在unordered_map中添加新的字符并初始化计数器为1
else {
charCounts[c] = 1;
}
}
// 输出字符及其出现次数
for (const auto& pair : charCounts) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}在上述示例中,我们首先创建了一个std::unordered_map<char, int>类型的变量charCounts,用于存储字符及其对应的出现次数。然后,我们遍历字符串中的每个字符,并使用unordered_map来统计字符出现的次数。最后,我们遍历charCounts并输出每个字符及其对应的出现次数。
请注意,std::unordered_map是C++标准库中的一个关联容器,用于存储键-值对。在这个示例中,字符被用作键,而整数被用作值,以表示字符的出现次数。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

