Start learning free

LESSON 12 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc in Rust: Choosing What to Count with a Mode Flag

Practice Read the full explanation

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

fn wc(lines: Vec<String>, mode: String) -> String

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines + "\t" + words + "\t" + chars.

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts in a single pass through lines, then branch on mode to pick the return value. split_whitespace() handles the word count for you.

let num_lines = lines.len();
let mut num_words = 0;
let mut num_chars = 0;
for line in &lines {
    num_words += line.split_whitespace().count();
    num_chars += line.chars().count();
}
Use .to_string() to convert numbers to strings.

The full solution:
impl Solution {
    fn wc(lines: Vec<String>, mode: String) -> String {
        let num_lines = lines.len();
        let mut num_words = 0;
        let mut num_chars = 0;
        for line in &lines {
            num_words += line.split_whitespace().count();
            num_chars += line.chars().count();
        }
        if mode == "l" { return num_lines.to_string(); }
        if mode == "w" { return num_words.to_string(); }
        if mode == "c" { return num_chars.to_string(); }
        return format!("{}\t{}\t{}", num_lines, num_words, num_chars);
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in Rust, explained

    Problem overview

    The third wc version combines the line, word and character counts behind one function: wc(lines: Vec<String>, mode: String) -> String. The mode says which count to return, and the result is always text:

    • "l" returns the number of lines.
    • "w" returns the number of words.
    • "c" returns the number of characters, with no newlines counted.
    • "all" returns the three counts in the order lines, words, characters, separated by tab characters.

    Any other mode gives the same result as "all", and modes are case-sensitive, so "L" is not "l". For lines = ["hello", "world"] and mode = "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters.

    Approach: count everything once, then pick

    The earlier versions each counted one thing. Here the simplest design computes all three counts first and lets the mode choose which one to return. That needs only a single pass over the lines, and the choice at the end is a few if statements.

    • The line count needs no loop: it is lines.len().
    • The word count adds split_whitespace().count() for each line, as in the word version.
    • The character count adds chars().count() for each line. The previous version used len(), which counts bytes. chars() walks the string by characters, so the count is right for any text. The two agree on ASCII.

    The order of the final checks matters. The three specific modes return early, and the last line, which builds the tab-separated text, runs for everything else. That is how "all", "x" and "L" all end up with the same result without being listed one by one.

    The cost of this design is that all three counts are computed even when the caller wants only one. That is fine for a tool whose time stays linear anyway, and it keeps the code short: the branching happens in one place, after the counting, instead of being mixed into the loop.

    Step by step

    1. Store the line count. let num_lines = lines.len(); is all it takes, and it doesn't change afterwards, so no mut is needed.
    2. Create the word total as let mut num_words = 0;, because it grows as lines are read.
    3. Create the character total the same way, as let mut num_chars = 0;.
    4. Loop over the lines by reference with for line in &lines, so the vector is borrowed and stays usable.
    5. Add the words of this line with split_whitespace().count(). A blank line adds nothing.
    6. Add the characters of this line with chars().count(). Spaces count, since they are part of the line.
    7. Return the line count for "l". to_string() turns the number into a String, because the function always returns text.
    8. Return the word count for "w" in the same way.
    9. Return the character count for "c" in the same way.
    10. Return all three counts as the last line. format! builds a String from a template in which each {} takes the next value, and \t in the template is a tab character.

    The solution in Rust

    impl Solution {
        fn wc(lines: Vec<String>, mode: String) -> String {
            let num_lines = lines.len();
            let mut num_words = 0;
            let mut num_chars = 0;
            for line in &lines {
                num_words += line.split_whitespace().count();
                num_chars += line.chars().count();
            }
            if mode == "l" {
                return num_lines.to_string();
            }
            if mode == "w" {
                return num_words.to_string();
            }
            if mode == "c" {
                return num_chars.to_string();
            }
            return format!("{}\t{}\t{}", num_lines, num_words, num_chars);
        }
    }
    

    Rust details worth knowing:

    • No casts this time. All three counts stay usize: len() and count() both return it, and the compiler infers that type for the two let mut totals. Since the function returns text, nothing needs to be converted to i32.
    • Comparing a String with a literal. mode == "l" compares a String with a &str by content. It doesn't compare addresses.
    • to_string() and format!. Integers implement to_string(), which gives their decimal digits. format! works like println!, but it returns the text instead of printing it.
    • Why mut only on two of them. num_lines is set once and never changes, while num_words and num_chars are updated on every pass of the loop. Rust makes a variable immutable unless you say otherwise, which tells the reader which values change.
    • Early returns. After a return inside an if, the function stops there. Code below runs only when no earlier branch matched.

    Complexity

    Time: O(m), where m is the total number of characters in all lines. Each line is scanned twice, once by split_whitespace() and once by chars(), which is still linear.

    Space: O(1) beyond the returned string. The counters are integers, and the result holds a handful of digits.

    Edge cases and common mistakes

    • Empty list. The loop never runs. "l", "w" and "c" each give "0", and "all" gives "0\t0\t0".
    • Unknown or differently cased modes. "x" and "L" fall through to the last line and give the same text as "all". Don't add a branch that rejects them.
    • Returning numbers. The function returns a String. Writing return num_lines; is a type error, so convert it with to_string().
    • A blank line is still a line. For ["a b c", "", " x"] the line count is 3, even though the middle line has no words. The word count is 4 and the character count is 9.
    • Counting the separators. As in the previous version, newlines between lines are not part of the character count.
    • Wrong order in the tab-separated result. It is lines, then words, then characters.

    Testing

    Here are inputs with the results the function returns, written as Rust string literals:

    • ["hello", "world"] with "all" gives "2\t2\t10".
    • ["hello", "world"] with "l" gives "2", with "w" gives "2" and with "c" gives "10".
    • ["hello", "world"] with "x" or "L" gives "2\t2\t10".
    • ["a b c", "", " x"] with "all" gives "3\t4\t9".
    • An empty vector with "all" gives "0\t0\t0".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free