Start learning free

LESSON 373 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v2 — First n Lines in C++

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.size(). If n is 0 the result is the empty string.

Function signature:

string head(vector<string> lines, int n)

Example:

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

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Loop from 0 to n - 1, accumulating each line. Insert a "\n" before every line except the first.

for (int i = 0; i < n; i++) {
    if (i > 0) result += "\n";
    result += lines[i];
}


The full solution:
class Solution {
public:
    string head(vector<string> lines, int n) {
        string result;
        for (int i = 0; i < n; i++) {
            if (i > 0) result += "\n";
            result += lines[i];
        }
        return result;
    }
};

STEP 1 OF 5
    Ctrl + Enter to check

    Head V2 in C++

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