Start learning free

LESSON 11 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc -m in Rust: Counting Characters with len()

Practice Read the full explanation

Build a tiny version of the character count of the Unix wc command. Given a list of lines, return the total number of characters across all lines as an integer.

Convention: count only the characters in each line — do not count the implicit newlines that separate them. Spaces and tabs inside a line count as one character each.

Note: this is a simplified version. The real wc -m also counts the newlines, and the real wc -c counts bytes, not characters. Here the answer is simply the sum of the line lengths. The input is plain ASCII text (other alphabets are counted differently by different languages).

Function signature:

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

Example:

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

Output: 10

"hello" has 5 chars and "world" has 5 chars, for a total of 10.

An empty line adds 0, and an empty list of lines gives 0.


Loop through the lines and accumulate lines[i].len() into an i32 running total.

The full solution:
impl Solution {
    fn count_chars(lines: Vec<String>) -> i32 {
        let mut total = 0;
        for i in 0..lines.len() {
            total += lines[i].len() as i32;
        }
        return total;
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Wc V3 in Rust, explained

    Problem overview

    This version of wc counts characters. The function count_chars receives a Vec<String> of lines and returns the total length of all lines as an i32. The lesson uses a simple convention: only the characters inside each line count, and the newlines that separate lines are not included. Spaces and tabs count as one character each.

    For lines = ["hello", "world"] the answer is 10, since each word has 5 characters. An empty line adds 0, and an empty list of lines gives 0. The input is plain ASCII text.

    Approach: add up the line lengths

    The answer is the sum of the lengths of the lines, so the structure is the same as in the word counter: a running total that starts at zero and grows by one amount per line. Only the amount changes. The word counter added the number of words in each line, and this version adds the line's length.

    In Rust, len() on a String returns the number of bytes in its UTF-8 encoding, not the number of characters. For ASCII text the two are the same, because every ASCII character takes exactly one byte. That is why len() is enough here, and why the lesson states that the input is ASCII.

    This lesson visits the lines by position instead of borrowing the vector. The loop variable i runs over 0..lines.len(), and lines[i] is the line at that position.

    Step by step

    1. Create the running total. Declare it with let mut and start it at 0: no line has been counted yet, and the value will change as the loop runs.
    2. Loop over the positions. for i in 0..lines.len() gives i every value from 0 up to the last valid index. The range excludes its upper end, so there is no off-by-one at the end of the vector.
    3. Add the length of the current line. lines[i].len() is the number of bytes in that line. It is a usize, so as i32 converts it to match the total.
    4. Return the total after the loop. It sits outside the loop so that it runs once, when all lines have been added.

    The solution in Rust

    impl Solution {
        fn count_chars(lines: Vec<String>) -> i32 {
            let mut total = 0;
            for i in 0..lines.len() {
                total += lines[i].len() as i32;
            }
            return total;
        }
    }
    

    Rust details worth knowing:

    • len() returns usize. The function must return an i32, and Rust never converts integer types implicitly, so the as i32 is needed. The compiler infers that total is an i32 from this +=.
    • Bytes against characters. The word "héllo" has 5 characters, but "héllo".len() is 6, because é takes two bytes in UTF-8. To count characters in general you would write s.chars().count(), which walks the string, decoding as it goes. The lesson's text is ASCII, so both give the same answer here.
    • Indexing the vector. lines[i] reads the element at position i and panics if i is out of range. Looping over 0..lines.len() keeps every index valid. The expression doesn't move the string out of the vector: calling len() on it only borrows it.
    • Looping by position or by reference. for line in &lines would give the same result with no indexing. The index version is useful when you also need the position, and it makes the "line at position i" picture explicit.

    Complexity

    Time: O(n), where n is the number of lines. A String stores its length, so len() takes constant time, and the loop does constant work per line.

    Space: O(1). The only extra value is the integer total.

    Edge cases and common mistakes

    • Counting the separators. The lesson does not add one character per line for the newline. For ["hello", "world"] the answer is 10, not 11.
    • Empty input. An empty vector never enters the loop, so the function returns 0. An empty string adds 0 as well.
    • Whitespace. Spaces and tabs are characters like any other. ["a b", "", "\tx"] gives 5: three characters, none, then two.
    • Non-ASCII text. This solution counts bytes. For ["héllo"] it returns 6, not 5. That is correct for the lesson's ASCII input, but a character count for arbitrary text would use chars().count().
    • Using the wrong range. 0..=lines.len() would include one index too many and panic on the last pass.

    Testing

    These inputs and the results the function returns for them are worth trying:

    • ["hello", "world"] gives 10.
    • ["a b", "", "\tx"] gives 5.
    • [""] gives 0.
    • An empty vector gives 0.
    • ["héllo"] gives 6, which shows the byte count.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free