Repeated Characters Via Entry

Count characters through a HashMap entry increment, keep counts above one, and sort the pairs so reports of repeated characters are complete and stable.

RustData Integrity

Code

rustsnippet
22 lines
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");
    }
}

Repeated Characters Via Entry: how the code works

Structurally, expect the function main and nothing else.

The cycling part of this snippet is for ch in sample.chars().

Points of care

  • Run it as-is; the project gains no new pieces.

Putting it to use

Anchor definition: fn main()

Core lines

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

Interactive Tools for This Topic

FAQ

How do you run Repeated Characters Via Entry?
Direct execution is enough; the script has no external requirements.