diff options
author | Lars Wirzenius <liw@liw.fi> | 2018-07-19 23:28:25 +0300 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2018-07-19 23:28:25 +0300 |
commit | f5f8c22f048012bff3ede3fbde194a7cc1f46801 (patch) | |
tree | 2eed624faa21d2ccf00a4c023dd2675e4589178d | |
parent | f0906d4b7601d08e3635883997a32982abb5f124 (diff) | |
download | wordfreq-f5f8c22f048012bff3ede3fbde194a7cc1f46801.tar.gz |
Change: use a HashMap to store word counts
-rw-r--r-- | src/main.rs | 39 |
1 files changed, 35 insertions, 4 deletions
diff --git a/src/main.rs b/src/main.rs index d12332c..f376742 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ use std::env; use std::fs::File; use std::io; use std::io::BufRead; +use std::collections::HashMap; @@ -18,22 +19,52 @@ fn main() -> io::Result<()> { fn print_words(reader: &mut io::BufReader<File>) -> io::Result<()> { for line in reader.lines() { let line = line?; - print_words_in_line(&line); + count_words_in_line(&line); } Ok(()) } -fn print_words_in_line(line: &str) { +fn count_words_in_line(line: &str) { + let mut words = WordCounts::new(); let mut word = String::new(); for c in line.chars() { if c.is_alphabetic() { word.push(c); } else { if !word.is_empty() { - println!("{}", word); + words.count(word.clone()); + word.clear(); } - word.clear(); + } + } + if !word.is_empty() { + words.count(word.clone()); + } + words.print(); +} + + +struct WordCounts { + counts: HashMap<String, u32>, +} + + +impl WordCounts { + fn new() -> Self { + WordCounts { + counts: HashMap::new(), + } + } + + fn count(&mut self, word: String) { + let counter = self.counts.entry(word).or_insert(0); + *counter += 1; + } + + fn print(&self) { + for (word, count) in self.counts.iter() { + println!("{} {}", count, word); } } } |