summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: f376742e872187a9400a5a86b5358df529ab5d7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::env;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::collections::HashMap;



fn main() -> io::Result<()> {
    for filename in env::args().skip(1) {
        let mut f = File::open(&filename)?;
        let mut reader = io::BufReader::new(f);
        print_words(&mut reader)?;
    }
    Ok(())
}


fn print_words(reader: &mut io::BufReader<File>) -> io::Result<()> {
    for line in reader.lines() {
        let line = line?;
        count_words_in_line(&line);
    }
    Ok(())
}


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() {
                words.count(word.clone());
                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);
        }
    }
}