Boss lesson · Unit 04
A word counter
Text split into words, counted in a map, sorted and reported
What you practise
- Text split into words, counted in a map, sorted and reported: most common first
Try a question from this lesson
Pick one
split_whitespace() hands out the pieces of a text that lie between spaces. How many lines does this print?
let text = "the cat saw the dog";
for word in text.split_whitespace() {
println!("{word}");
}Correct answer
5
Why
The text has five words, and the loop runs once for each, repeats included. Every word is a &str: a borrowed view into the original text, with nothing copied.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Sorting pairs
A map has no order, but a vector can be sorted.
Tuples compare by their first part, then by their second. So put the count first: (count, word).
sort() puts the smallest first. reverse() flips the vector, so the biggest count comes to the top.
let mut pairs = vec![
(1, "cat"), (2, "the"), (1, "saw"),
];
pairs.sort();
println!("{:?}", pairs);
pairs.reverse();
println!("{:?}", pairs[0]);11 more exercises in the app
- 3× type the answer
- 1× order the lines
- 2× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.