From 7f9392e83b6795828e7cd3f82d80d24bf247fe25 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Thu, 12 Jul 2018 20:30:39 +0300 Subject: Change: do more in Count methods directly --- src/main.rs | 70 +++++++++++++++++++++++++------------------------------------ 1 file changed, 29 insertions(+), 41 deletions(-) diff --git a/src/main.rs b/src/main.rs index 32ffb18..4404d8b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,28 +28,51 @@ impl Count { self.chars += c.chars; } - fn incr_lines(&mut self) { + fn count(&mut self, line: &str) { + self.count_line(); + self.count_words_in_line(line); + self.count_chars_in_line(line); + } + + fn count_line(&mut self) { self.lines += 1; } - fn incr_words(&mut self, n: usize) { - self.words += n; + fn count_words_in_line(&mut self, line: &str) { + let mut in_word = false; + + for c in line.chars() { + if c.is_alphabetic() { + if !in_word { + in_word = true; + self.words += 1; + } + } else { + in_word = false; + } + } } - fn incr_chars(&mut self, n: usize) { - self.chars += n; + fn count_chars_in_line(&mut self, line: &str) { + // add +1 for newline, which we ASSUME is there + self.chars += line.chars().count() + 1; } } fn main() -> Result<(), io::Error> { + let mut total = Count::new(); for filename in env::args().skip(1) { let mut f = File::open(&filename)?; let mut reader = io::BufReader::new(f); let c = wc(&mut reader)?; + total.add(&c); println!("{:>5} {:>5} {:>5} {}", c.lines, c.words, c.chars, filename); } + if env::args().skip(1).count() > 1 { + println!("{:>5} {:>5} {:>5} {}", total.lines, total.words, total.chars, "total"); + } Ok(()) } @@ -58,42 +81,7 @@ fn wc(reader: &mut io::BufReader) -> Result { let mut count = Count::new(); for line in reader.lines() { let line = line?; - count.add(&count_line(&line)); + count.count(&line); } Ok(count) } - - -fn count_line(line: &str) -> Count{ - let mut count = Count::new(); - - // we have a line! - count.incr_lines(); - - // add +1 for newline, which we ASSUME is there - count.incr_chars(line.chars().count() + 1); - - // count words - count.incr_words(count_line_words(line)); - - count -} - - -fn count_line_words(line: &str) -> usize { - let mut in_word = false; - let mut num_words = 0; - - for c in line.chars() { - if c.is_alphabetic() { - if !in_word { - in_word = true; - num_words += 1; - } - } else { - in_word = false; - } - } - - num_words -} -- cgit v1.2.1