Start learning free

LESSON 25 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr in Go: Swap One Character with strings.ReplaceAll

Practice Read the full explanation

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

    GO · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in Go, explained

    Problem overview

    This is the first version of a small tr command. The function tr takes a slice of lines and two single-character strings, fromChar and toChar. It replaces every fromChar with toChar in each line and returns the lines joined by "\n".

    The characters are single ASCII characters taken literally, with no escapes or ranges. Upper and lower case differ. A line may be empty or may not contain fromChar at all. For ["banana", "apple"] with "a" and "X" the result is "bXnXnX\nXpple".

    Approach: translate each line, then join

    Each line is translated independently, so the work is a loop over the lines. The standard library already has the translation: strings.ReplaceAll(s, old, new) returns a copy of s with every non-overlapping occurrence of old replaced by new. Collect the translated lines in a slice, then glue them together with strings.Join, which puts the separator between the lines only.

    You could also walk each line character by character and build the new text by hand, but a single character swap is exactly what ReplaceAll is for, so the lesson uses it. Because every line is treated the same way, an empty line needs no special case: replacing inside an empty string gives an empty string. The next version builds on this one.

    Step by step

    1. Create result as an empty slice of strings with :=. The translated lines collect in it.
    2. Loop with range over lines, taking each line. Range gives an index and a value; the blank identifier _ discards the index, since it isn't needed.
    3. Inside the loop, append strings.ReplaceAll(line, fromChar, toChar) to result, and assign the slice that append returns back to result.
    4. After the loop, return strings.Join(result, "\n"). It runs once, after every line is translated.

    The solution in Go

    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")
    }
    

    Go details to notice:

    • Strings are immutable. strings.ReplaceAll does not change line. It returns a new string. Calling it and ignoring the result leaves the line as it was: after strings.ReplaceAll(line, "a", "X") with the result discarded, line is still banana.
    • The parameters are strings, not bytes. fromChar and toChar have type string even though each holds one character, so they pass straight to ReplaceAll.
    • for _, line := range lines is the idiomatic way to visit every element. line is a copy of the element, which is fine because only a read is needed.
    • append returns a slice, so its result goes back into result. Go does not allow discarding it.
    • strings.Join adds no trailing newline. The separator goes between two lines only.

    Complexity

    Time: O(L), where L is the total number of characters in all lines. Each line is scanned once by ReplaceAll and once more when the result is joined.

    Space: O(L) for the translated lines and the joined string.

    Edge cases and common mistakes

    • Case matters. ["banana", "apple"] with "A" and "X" returns "banana\napple", unchanged.
    • Empty lines survive. ["", "aa", "b"] with "a" and "-" gives "\n--\nb". The empty line stays and appears as a blank first line.
    • Special characters need no escaping. ["a.b.c"] with "." and "/" gives "a/b/c". ReplaceAll matches plain text, not patterns.
    • Replacing only the first match. strings.Replace(s, old, new, 1) changes a single occurrence: strings.Replace("banana", "a", "X", 1) returns bXnana. ReplaceAll changes them all.
    • Discarding the result. Because strings are immutable, the translated text must be kept.
    • No lines. An empty slice gives "".

    Testing

    • ["banana", "apple"], "a", "X" gives "bXnXnX\nXpple".
    • ["banana", "apple"], "A", "X" gives "banana\napple".
    • ["", "aa", "b"], "a", "-" gives "\n--\nb".
    • ["a.b.c"], ".", "/" gives "a/b/c".
    • An empty slice gives "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free