实现说明
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");
}
}