Start learning free

LESSON 25 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in Swift: Swapping One Character with replacingOccurrences

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

Swift's String.replacingOccurrences(of:with:) swaps EVERY occurrence. Apply it to each line and accumulate.

The full solution:
class Solution {
    func tr(_ lines: [String], _ fromChar: String, _ toChar: String) -> String {
        var result = [String]()
        for line in lines {
            result.append(line.replacingOccurrences(of: fromChar, with: toChar))
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in Swift, explained

    Problem overview

    The first version of the tr tool swaps one character for another. tr(_ lines: [String], _ fromChar: String, _ toChar: String) -> String replaces every fromChar with toChar in each line and returns the lines joined with "\n". Both arguments are single ASCII characters, taken literally, and case matters. A line may be empty or may not contain fromChar at all.

    For ["banana", "apple"], "a" and "X" the result is "bXnXnX\nXpple".

    Approach: translate each line, then join

    The work is per line, and lines don't affect each other. Walk through the array, translate each line, collect the results in a new array, and join them at the end. Swift's replacingOccurrences(of:with:) does the translation in one call. It looks for the first string, replaces every match with the second and returns a new string. The original line is not modified.

    Both parameters are typed String, even though they hold one character each. That matches what replacingOccurrences expects, so there is nothing to convert.

    The loop could also be written with map, as lines.map { $0.replacingOccurrences(of: fromChar, with: toChar) }.joined(separator: "\n"), which gives the same "bXnXnX\nXpple" for the example. The explicit loop is easier to follow while you learn, and it matches the lesson's steps. Whichever you choose, the idea is the same: translate each line on its own, then join.

    This tool is the smallest member of a family. The tr command in a shell translates characters read from its input, and this version handles only one pair of characters. The next version builds on it.

    Step by step

    1. Create result as an empty [String] with var. Each translated line is added to it.
    2. Loop with for line in lines. Each line is a whole line of text, not a single character.
    3. Append the translated line with line.replacingOccurrences(of: fromChar, with: toChar). It replaces all matches, not just the first.
    4. Return result.joined(separator: "\n") after the loop. It runs once, and the separator goes between lines only, so there is no newline after the last line.

    The solution in Swift

        func tr(_ lines: [String], _ fromChar: String, _ toChar: String) -> String {
            var result = [String]()
            for line in lines {
                result.append(line.replacingOccurrences(of: fromChar, with: toChar))
            }
            return result.joined(separator: "\n")
        }
    

    Details that matter:

    • replacingOccurrences comes from Foundation. It isn't part of the Swift standard library. In a file of your own, add import Foundation at the top. Without it the compiler reports value of type 'String' has no member 'replacingOccurrences'.
    • Strings are values. The method returns a new string, so line keeps its old text. That's why the result has to be stored: result.append(...) receives the new string.
    • Case matters. The search is exact, so "Banana" with "b" and "X" stays "Banana".
    • Empty lines pass through. An empty line has nothing to replace, so it stays empty and still takes its place in the output.
    • [String](). It creates an empty array of strings; var result: [String] = [] is an equivalent spelling.

    Complexity

    Time: O(total characters), since each line is scanned once for matches and copied once. Space: O(total characters) for the translated lines and the joined result.

    Edge cases and common mistakes

    • Lines without the character. They come out unchanged.
    • Empty lines. ["banana", "", "cherry"] with "a" and "X" returns "bXnXnX\n\ncherry". The empty line becomes an empty piece between two newlines.
    • Empty input. An empty list returns "".
    • Forgetting to use the return value. Calling line.replacingOccurrences(...) without storing the result changes nothing, because strings are not modified in place.
    • Special characters. The characters are literal, so "." is an ordinary dot here. ["a.b.c"] with "." and "-" returns "a-b-c".
    • Trailing newline. Joining with "\n" adds no newline after the last line.

    Testing

    • ["banana", "apple"], "a", "X" gives "bXnXnX\nXpple".
    • ["banana", "", "cherry"], "a", "X" gives "bXnXnX\n\ncherry".
    • ["Banana"], "b", "X" gives "Banana".
    • ["a.b.c"], ".", "-" gives "a-b-c".
    • [], "a", "X" gives "".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free