wordcount.rs in Rust
A complete word-frequency program: read stdin, tally, sort, print.
use std::collections::HashMap;
use std::io::{self, Read};
fn main() {
let mut input = String::new();
io::stdin()
.read_to_string(&mut input)
.expect("failed to read stdin");
let mut counts: HashMap<String, usize> = HashMap::new();
for raw in input.split_whitespace() {
let word: String = raw
.trim_matches(|c: char| c.is_ascii_punctuation())
.to_lowercase();
if !word.is_empty() {
*counts.entry(word).or_insert(0) += 1;
}
}
let mut pairs: Vec<_> = counts.into_iter().collect();
pairs.sort_by(|a, b| b.1.cmp(&a.1));
for (word, count) in pairs.into_iter().take(10) {
println!("{count:6} {word}");
}
}
Keywords and builtins used here
HashMapStringVeccharfnforifinletmainmutselfuseusize
The run, in numbers
- Lines
- 25
- Characters to type
- 602
- Tokens
- 198
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 108 seconds.
Step 1 of 1 in Encore, step 14 of 14 in Iterators & closures.