c++ 统计字符出现频率代码
时间: 2024-11-18 21:27:49 浏览: 88
在C++中,统计字符串中字符出现的频率通常涉及到容器如`std::map`或`std::unordered_map`,以及遍历数组的操作。这里是一个简单的示例代码:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::string str = "Hello, World!";
std::unordered_map<char, int> charCount;
// 遍历字符串并更新字符计数
for (char c : str) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { // 只考虑字母,可根据需要调整
charCount[c]++;
}
}
// 输出每个字符及其出现次数
for (const auto &pair : charCount) {
std::cout << "Character '" << pair.first << "' appears " << pair.second << " times.\n";
}
return 0;
}
```
在这个例子中,我们创建了一个`std::unordered_map`来存储字符及其对应的出现次数。然后遍历输入字符串,对于每一个字母字符,我们在映射中增加其对应的计数值。最后,我们打印出每个字符及其出现的次数。
阅读全文
相关推荐


















