Skip to content

Commit

Permalink
cii: Add rust implementation of word count
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Nov 26, 2023
1 parent e0a2784 commit 426c3cd
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions cii/tests/word_count.rs
Original file line number Diff line number Diff line change
@@ -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::<String, usize>::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();
}
}

0 comments on commit 426c3cd

Please sign in to comment.