Start learning free

LESSON 616 OF 679 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: wc v2 — Count Words

Practice

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