Start learning free

LESSON 373 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v1 — Print Lines in Rust

Practice

Build a tiny version of the Unix cat command. Given a list of lines, return them joined by newline characters (\n) so they print one per line.

Lines can be blank, and the list can be empty (the result is then an empty string).

Function signature:

fn cat(lines: Vec<String>) -> String

Example:

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

Output: "hello\nworld\nfoo"

When printed:
hello
world
foo

Build the result manually: walk through the lines in order and accumulate them into a single String, inserting a "\n" between every pair.

A clean trick: only prepend "\n" when i > 0. That way the first line has no separator before it, and every subsequent line is preceded by exactly one newline.
let mut result = String::new();
for i in 0..lines.len() {
    if i > 0 {
        result += "\n";
    }
    result += &lines[i];
}


The full solution:
impl Solution {
    fn cat(lines: Vec<String>) -> String {
        let mut result = String::new();
        for i in 0..lines.len() {
            if i > 0 {
                result += "\n";
            }
            result += &lines[i];
        }
        return result;
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    Cat V1 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