diff --git a/cii/tests/word_count.rs b/cii/tests/word_count.rs new file mode 100644 index 00000000..207d08a7 --- /dev/null +++ b/cii/tests/word_count.rs @@ -0,0 +1,33 @@ +use std::collections::BTreeMap; +use std::env; +use std::fs::File; +use std::io::{self, BufRead, BufReader}; + +fn word_count(filename: &str) -> Result<(), io::Error> { + let fd = File::open(filename)?; + let reader = BufReader::new(fd); + let mut counts = BTreeMap::::new(); + + for line in reader.lines() { + let line = line?; + for word in line.split_ascii_whitespace() { + if let Some(count) = counts.get_mut(word) { + *count += 1; + } else { + counts.insert(word.to_owned(), 1); + } + } + } + + for (key, value) in &counts { + println!("{key}: {value}"); + } + + Ok(()) +} + +fn main() { + for arg in env::args().skip(1) { + word_count(&arg).unwrap(); + } +}