Start learning free

LESSON 387 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v1 — Single Char Swap in Go

Practice

Build a tiny version of the Unix tr command. Given a list of lines and two single characters fromChar and toChar, replace every occurrence of fromChar with toChar in each line, then return the lines joined by newline characters (\n).

Notes: fromChar and toChar are single ASCII characters, taken literally (no escapes like \, no ranges). Upper and lower case are different characters. A line may be empty, and may not contain fromChar at all.

Function signature:

func tr(lines []string, fromChar string, toChar string) string

Example:

Input: lines = ["banana", "apple"], fromChar = "a", toChar = "X"

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

Go's strings.ReplaceAll(s, old, new) swaps EVERY occurrence. Collect the translated lines into a []string and join them with strings.Join(result, "\n").

The full solution:
func tr(lines []string, fromChar string, toChar string) string {
    result := []string{}
    for _, line := range lines {
        result = append(result, strings.ReplaceAll(line, fromChar, toChar))
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 4
    Ctrl + Enter to check

    Tr 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