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.
Code
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
Word Frequency CounterCount word occurrences in text with Unicode-aware tokenization, optional lowercasing, and a ranked frequency table.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.