Start learning free

LESSON 10 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc -w in Rust: Counting Words with split_whitespace

Practice Read the full explanation

Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.

Function signature:

fn count_words(lines: Vec<String>) -> i32

Example:

Input: lines = ["hello world", "foo bar baz", ""]

Output: 5

The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.

Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.


Iterate over the lines and accumulate the word count. Empty lines must contribute zero.

Use line.split_whitespace().count(): it skips runs of whitespace and yields nothing for an empty or whitespace-only line. Cast the count to i32 with as i32.

The full solution:
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;
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in Rust, explained

    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

    1. Create the running total. Declare it with let mut and 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.
    2. Loop over the lines by reference. for line in &lines borrows the vector and gives line as a &String on each pass. Without the &, the loop would take ownership of the vector and consume it.
    3. Add this line's words to the total. Inside the loop, line.split_whitespace().count() gives the number of words. It is a usize, so as i32 converts it to match the return type. A blank line adds 0.
    4. 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 writes let mut total: i32. The compiler infers i32 from the += with an i32 value and from the return type.
    • The cast. count() returns a usize, and Rust never converts between integer types on its own, so the as i32 is required. A cast with as truncates 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 just total, without return and 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. Use split_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 &. With for line in lines, the vector is moved into the loop and can't be used afterwards. With &lines it is only borrowed.
    • Mixing up the types. Adding the usize from count() straight to an i32 total is a compile error. Convert it with as 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.

    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free