Start learning free

LESSON 383 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: wc v3 — Count Characters in Rust

Practice

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

    Wc V3 in Rust

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