others-rust tutorials-1-how to count number of words using rust?
1. Purpose
In this post, I will try to use rust language to count the number of words in a sentence.
2. Solution
2.1 Show me the code
Talk is cheap, show me the code:
fn count_word() {
let text = "Don't say hello to boys again, boys. Just don't say it."; // line 1
let mut map = HashMap::new(); //line 2
let v:Vec<&str> = text.split_terminator(&[' ', ',','.'][..]).collect(); // line 3
for word in v {
let count = map.entry(word.to_lowercase()).or_insert(0); // line 4
*count+=1; //line 5
}
println!("{:?}",map); // line 6
}
run the above code, we get this:
➜ rust-tutorial-1 git:(main) cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.05s
Running `target/debug/rust-tutorial-1`
{"boys": 2, "hello": 1, "don't": 2, "say": 2, "": 2, "it": 1, "to": 1, "again": 1, "just": 1}
2.2 Code explanation
- line 1: I just declared a string literal.
let text = "Don't say hello to boys again, boys. Just don't say it."; // line 1
- line 2: I defined a HashMap
let mut map = HashMap::new(); //line 2
- line 3: This is the key point, I use the
.split_termiator
to split the string into words, I passed an array of terminator characters to.split_terminator
, rust string will be splited by those characters. It’s awesome.let v:Vec<&str> = text.split_terminator(&[' ', ',','.'][..]).collect(); // line 3
Some examples of
.split_terminator
:let mut split = "A..B..".split_terminator('.'); assert_eq!(split.as_str(), "A..B.."); split.next(); assert_eq!(split.as_str(), ".B.."); split.by_ref().for_each(drop); assert_eq!(split.as_str(), "");
- line 4: I use HashMap’s
.entry
function to check if the word exists in the map, if not , it will be inserted to the map with the value 0, and then the reference to0
is returned as variablecount
let count = map.entry(word.to_lowercase()).or_insert(0); // line 4
- line 5: I increased the variable
count
,because it’s already bound to the word in the map, so the count of the word is increased.*count+=1; //line 5
- line 6: I use the trait ‘Debug’ of HashMap to print the key and values in the map
println!("{:?}",map); // line 6
2.3 The code example is in github.com
You can find the whole code examples on github.com: rust-tutorials-1
3. Summary
In this post, I demonstrated how to count the number of words in a rust string using .split_terminator
of string and .entry
of HashMap. That’s it, thanks for your reading.