You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中将字符串转换为统计各字符出现次数的映射字典

C++ 实现字符串字符频次统计的方案

C++ 完全支持你想要的 my_map[key]++ 简便写法,不需要手动转 char* 数组,直接遍历 std::string 的每个字符即可,以下是可直接运行的实现示例:

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::string input = "letter";
    // 定义 key 为 char、value 为 int 的哈希表存储计数
    std::unordered_map<char, int> char_count;

    // 遍历字符串每个字符,直接累加计数
    for (char c : input) {
        char_count[c]++;
    }

    // 输出统计结果
    for (const auto& pair : char_count) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

运行上述代码输入为 letter 时,输出结果和你给出的示例一致:

l: 1
e: 2
t: 2
r: 1

可选优化方案

  • 如果需要按字符 ASCII 顺序输出结果,把 std::unordered_map 替换成 std::map 即可,std::map 会自动按 key 的顺序排序。
  • 如果仅需要统计可打印 ASCII 字符,也可以用长度为 128 的数组实现,性能更高:
#include <iostream>
#include <string>

int main() {
    std::string input = "letter";
    int char_count[128] = {0}; // 初始化所有计数为0

    for (char c : input) {
        char_count[static_cast<unsigned char>(c)]++;
    }

    // 遍历输出存在的字符
    for (int i = 0; i < 128; i++) {
        if (char_count[i] > 0) {
            std::cout << static_cast<char>(i) << ": " << char_count[i] << std::endl;
        }
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:45:05