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
- Create
resultas an empty slice of strings with:=. The translated lines collect in it. - Loop with
rangeoverlines, taking eachline. Range gives an index and a value; the blank identifier_discards the index, since it isn't needed. - Inside the loop, append
strings.ReplaceAll(line, fromChar, toChar)toresult, and assign the slice thatappendreturns back toresult. - 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.ReplaceAlldoes not changeline. It returns a new string. Calling it and ignoring the result leaves the line as it was: afterstrings.ReplaceAll(line, "a", "X")with the result discarded,lineis stillbanana. - The parameters are strings, not bytes.
fromCharandtoCharhave typestringeven though each holds one character, so they pass straight toReplaceAll. for _, line := range linesis the idiomatic way to visit every element.lineis a copy of the element, which is fine because only a read is needed.appendreturns a slice, so its result goes back intoresult. Go does not allow discarding it.strings.Joinadds 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".ReplaceAllmatches 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)returnsbXnana.ReplaceAllchanges 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
"".
