count words from stdin

Chen Wei 1 year ago
commit 5da2677772c8d973ca812b4f381e91dcd1059534
3 changed files with 23 additions and 0 deletions
+1-0.gitignore ADDED
View File
@@ -0,0 +1 @@
1+/target
+6-0Cargo.toml ADDED
View File
@@ -0,0 +1,6 @@
1+[package]
2+name = "wc-rs"
3+version = "0.1.0"
4+edition = "2021"
5+
6+[dependencies]
+16-0src/main.rs ADDED
View File
@@ -0,0 +1,16 @@
1+use std::collections::HashMap;
2+use std::io::{self, Read};
3+
4+fn main() {
5+ let mut text = String::new();
6+ io::stdin().read_to_string(&mut text).unwrap();
7+ let mut counts: HashMap<String, usize> = HashMap::new();
8+ for word in text.split_whitespace() {
9+ *counts.entry(word.to_lowercase()).or_insert(0) += 1;
10+ }
11+ let mut top: Vec<_> = counts.into_iter().collect();
12+ top.sort_by(|a, b| b.1.cmp(&a.1));
13+ for (word, n) in top.iter().take(10) {
14+ println!("{n:>6} {word}");
15+ }
16+}