Start learning free

LESSON 368 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v2 — First n Lines in Go

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

Function signature:

func head(lines []string, n int) string

Example:

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

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

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

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


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

STEP 1 OF 6
    Ctrl + Enter to check

    Head V2 in Go

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