Skip to content

Commit c1f77b2

Browse files
committed
feat: update word count application
1 parent 525c02f commit c1f77b2

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

word-count-parham/src/main.rs

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,56 +2,56 @@ use std::fs::File;
22
use std::io::{self, Read};
33

44
#[derive(Debug)]
5-
struct Options {
6-
delimiter: String,
5+
struct Options<'a> {
6+
delimiter: &'a str,
77
debug: bool,
88
}
99

1010
fn main() {
1111
let mut option = Options {
12-
delimiter: " ".to_string(),
12+
delimiter: " ",
1313
debug: false,
1414
};
1515
let args: Vec<String> = std::env::args().skip(1).collect();
16-
let mut file_names: Vec<String> = Vec::new();
16+
let mut file_names: Vec<&str> = Vec::new();
1717

1818
let mut i = 0;
1919
while i < args.len() {
2020
if args[i].starts_with("--") {
2121
match args[i].trim_start_matches("--") {
2222
"delimiter" => match args.get(i + 1) {
2323
Some(value) => {
24-
option.delimiter = value.clone();
24+
option.delimiter = value;
2525
i += 1;
2626
}
27-
None => panic!("delimiter needs a value"),
27+
None => panic!("--delimiter needs a value"),
2828
},
2929
"debug" => match args.get(i + 1) {
3030
Some(value) => {
3131
match value.to_lowercase().as_str() {
3232
"true" => option.debug = true,
3333
"false" => option.debug = false,
34-
_ => panic!("debug can be true or false"),
34+
_ => panic!("--debug can be true or false"),
3535
}
3636
i += 1;
3737
}
38-
None => panic!("delimiter needs a value"),
38+
None => panic!("--debug needs a value"),
3939
},
4040
&_ => {
4141
panic!("option {} not supported", args[i])
4242
}
4343
}
4444
} else {
45-
file_names.push(args[i].clone());
45+
file_names.push(&args[i]);
4646
}
4747
i += 1
4848
}
4949

50-
println!("{:?}", option);
50+
println!("{:#?}\nFiles: {:#?}", option, file_names);
5151

5252
let mut count: usize = 0;
5353
for file_name in file_names {
54-
count += count_words_from_file(&file_name, &option)
54+
count += count_words_from_file(file_name, &option)
5555
.unwrap_or_else(|err| panic!("cannot open {} {}", file_name, err))
5656
}
5757

@@ -64,11 +64,8 @@ fn count_words_from_file(file_name: &str, option: &Options) -> Result<usize, io:
6464
f.read_to_string(&mut s)?;
6565

6666
if option.debug {
67-
println!(
68-
"{:?}",
69-
s.split(option.delimiter.as_str()).collect::<Vec<&str>>()
70-
);
67+
println!("{:?}", s.split(option.delimiter).collect::<Vec<&str>>());
7168
}
7269

73-
Ok(s.split(option.delimiter.as_str()).count())
70+
Ok(s.split(option.delimiter).count())
7471
}

0 commit comments

Comments
 (0)