Word Frequency With Split Whitespace

Count word frequencies by feeding split_whitespace into a HashMap entry, then rank the aggregated pairs with a tie-broken sort for reproducible output.

RustData Integrity

Code

rustsnippet
21 lines
use std::collections::HashMap;

fn main() {
    let text = "deploy the api deploy the worker restart the api and the worker";

    // split_whitespace 是惰性迭代器,边遍历边统计,不先收集整个词表;
    // 词是 &str,借用 text,无逐词分配
    let mut counts: HashMap<&str, u32> = HashMap::new();
    for word in text.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }

    // 聚合后按次数降序、同次数按单词升序:输出可复现
    let mut ranked: Vec<_> = counts.into_iter().collect();
    ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));

    for (word, count) in ranked.iter().take(3) {
        println!("{count}x {word}");
    }
    println!("unique words: {}", ranked.len());
}

Inside the snippet

Word Frequency With Split Whitespace is built around the function main.

for word in text.split_whitespace() is the loop that carries the per-item work.

Putting it to use

Running the file prints labeled results such as unique words: — each operation’s effect is visible in the output.

Core lines

for (word, count) in ranked.iter().take(3) {
println!("{count}x {word}");
}
let mut ranked: Vec<_> = counts.into_iter().collect();

Interactive Tools for This Topic

FAQ

What does Word Frequency With Split Whitespace print when run?
Running the file directly is enough — expect labeled output lines such as `unique words:`.