-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
cii: Add rust implementation of word count
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |