Start learning free

LESSON 378 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v2 — First n Lines in Rust

Practice

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.len(). If n is 0 the result is the empty string.

Function signature:

fn head(lines: Vec<String>, n: i32) -> String

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Loop with i over 0..n, accumulating each line into a String. Insert a "\n" before every line except the first.

for i in 0..n {
    if i > 0 {
        result += "\n";
    }
    result += &lines[i as usize];
}


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

STEP 1 OF 6
    Ctrl + Enter to check

    Head V2 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