Start learning free

LESSON 383 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v1 — Ascending Alphabetical Sort in Go

Practice

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

func sortLines(lines []string) string

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Copy the slice so you don't reorder the caller's data, sort it with sort.Strings, then combine the lines with strings.Join using "\n".

The full solution:
func sortLines(lines []string) string {
    sortedLines := append([]string{}, lines...)
    sort.Strings(sortedLines)
    return strings.Join(sortedLines, "\n")
}

STEP 1 OF 4
    Ctrl + Enter to check

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