Problem overview
This version of the wc tool counts words. The function count_words receives a Vec<String> of lines and returns the total number of words across all of them as an i32. A word is a run of characters with no spaces or tabs inside it.
For lines = ["hello world", "foo bar baz", ""] the answer is 5: the first line has 2 words, the second has 3, and the empty line has none. Extra spaces or tabs between words, and at the start or end of a line, don't matter. A line that is empty or holds only whitespace adds 0, and an empty list of lines gives 0.
Approach: count the words of each line and add them up
The lines are independent: a word never spans two of them. So the job splits into two small tasks. Count the words of one line, then add the counts of all lines into a running total.
Counting the words of one line looks like it needs careful code, because of repeated spaces, tabs and blank edges. Rust's string type already solves it. split_whitespace() returns an iterator over the pieces of a string that are separated by whitespace, and it skips every run of whitespace as a single gap. Leading and trailing whitespace produce no pieces, and a string with no words produces an iterator that is empty from the start. Calling count() on the iterator consumes it and returns how many pieces there were.
Compare it with split(' '), which splits at each single space character. On "a b", with two spaces, it produces three pieces, "a", "" and "b", so counting its pieces would give 3 instead of 2. split_whitespace() doesn't have this problem, which is why it is the right tool here.
Step by step
- Create the running total. Declare it with
let mutand start it at 0. It has to be mutable because it changes on every line, and it starts at zero because no line has been counted yet. - Loop over the lines by reference.
for line in &linesborrows the vector and giveslineas a&Stringon each pass. Without the&, the loop would take ownership of the vector and consume it. - Add this line's words to the total. Inside the loop,
line.split_whitespace().count()gives the number of words. It is ausize, soas i32converts it to match the return type. A blank line adds 0. - Return the total after the loop. The return sits outside the loop because it must run once, after every line has been counted.
The solution in Rust
impl Solution {
fn count_words(lines: Vec<String>) -> i32 {
let mut total = 0;
for line in &lines {
total += line.split_whitespace().count() as i32;
}
return total;
}
}
Some details worth knowing:
- Type inference for
total. The code never writeslet mut total: i32. The compiler infersi32from the+=with ani32value and from the return type. - The cast.
count()returns ausize, and Rust never converts between integer types on its own, so theas i32is required. A cast withastruncates silently when the value doesn't fit, but a line would need over two billion words for that to matter here. - What counts as whitespace.
split_whitespace()splits on any Unicode whitespace character, not just the space and the tab, so a newline inside a string also separates words. The lesson's input is plain ASCII, where spaces and tabs are what you will meet. - Explicit
return. The last line could also be written as justtotal, withoutreturnand the semicolon. Both forms mean the same thing.
Complexity
Time: O(m), where m is the total number of characters in all lines. Each line is scanned once while its words are counted, and the loop does a constant amount of other work per line.
Space: O(1). The iterator hands out slices of the existing string, so nothing is copied, and the only extra value is the integer total.
Edge cases and common mistakes
- Splitting on a single space.
split(' ')counts empty pieces between repeated spaces and at the edges of a line. Usesplit_whitespace(). - Counting lines that look empty. A line made only of spaces or tabs has no words.
split_whitespace()handles it like an empty string. - Forgetting the
&. Withfor line in lines, the vector is moved into the loop and can't be used afterwards. With&linesit is only borrowed. - Mixing up the types. Adding the
usizefromcount()straight to ani32total is a compile error. Convert it withas i32. - Returning inside the loop. A
return total;placed in the loop body would end the function after the first line.
Testing
These inputs and the results the function returns for them are worth trying:
["hello world", "foo bar baz", ""]gives 5.[" hello \t world ", " ", "a"]gives 3: the tab and the extra spaces are ignored, and the whitespace-only line adds nothing.["a\t\tb c"]gives 3.["one"]gives 1.["", "\t "]gives 0.- An empty vector gives 0.
Try them in the editor above.
