typestar

Word count with HashMap in Rust

Tallies word frequencies in a HashMap, using the entry API.

fn word_count(text: &str) -> HashMap<String, usize> {
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        *counts.entry(word.to_lowercase()).or_insert(0) += 1;
    }
    counts
}

Keywords and builtins used here

The run, in numbers

Lines
7
Characters to type
189
Tokens
58
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 35 seconds.

Type this snippet

Step 2 of 2 in Maps & counting, step 13 of 14 in Iterators & closures.

← Previous Next →