← 中文资源

简体中文版本

entry 统计重复字符

逐字符走 HashMap entry 累加计数,不存在就插入 0、存在就原地加一;过滤掉只出现一次的字符,再按键排序输出,重复字符报告完整且顺序稳定可复现。

阅读英文原文

实现说明

entry 统计重复字符以函数 main为骨架。 这个示例中仅有的重复出现在 for ch in sample.chars() 里。

常见问题

「entry 统计重复字符」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

核心语句

.filter(|(_, count)| *count > 1)
.collect();

代码示例

use std::collections::HashMap;

fn main() {
    let sample = "mississippi";
    let mut counts: HashMap<char, usize> = HashMap::new();

    for ch in sample.chars() {
        // entry:不存在插入 0,存在原地累加,一次查询完成
        *counts.entry(ch).or_insert(0) += 1;
    }

    // 只保留 repeated characters,再排序让输出顺序稳定
    let mut repeated: Vec<(char, usize)> = counts
        .into_iter()
        .filter(|(_, count)| *count > 1)
        .collect();
    repeated.sort_unstable();

    for (ch, count) in &repeated {
        println!("{ch} appears {count} times");
    }
}