#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjj";
int len = str.length();
map<char, int> _map;
for (int i = 0; i < len; ++i)
{
auto ite1 = _map.find(str[i]); //find方法的原理自行百度!
if (ite1 != _map.end())
{
++((*ite1).second);
}
else
{
_map.insert(pair<char, int>(str[i], 1));
}
}
map<char, int>::iterator ite = _map.begin();
for (ite; ite != _map.end(); ++ite)
{
std::cout << (*ite).first << " " << (*ite).second << std::endl;
}
/*
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
*/
}
C++ 使用map统计给定字符串中的字符出现的次数
最新推荐文章于 2024-03-24 14:47:00 发布
该博客展示了一个C++程序,用于统计输入字符串中每个字符出现的频率。程序利用`std::map`存储字符及其对应的计数,遍历字符串并更新映射表。最终,程序打印出每个字符及其出现次数。
1202

被折叠的 条评论
为什么被折叠?



