Start learning free

LESSON 25 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in Scala: Replacing a Character in Every Line

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:

def tr(lines: Array[String], fromChar: String, toChar: String): String

Example:

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

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

Scala strings expose Java's replace(CharSequence, CharSequence), which swaps EVERY occurrence. Apply it to each line and accumulate.

The full solution:
class Solution {
    def tr(lines: Array[String], fromChar: String, toChar: String): String = {
        val result = scala.collection.mutable.ArrayBuffer[String]()
        for (line <- lines) {
            result += line.replace(fromChar, toChar)
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in Scala, explained

    Problem overview

    The tr project rebuilds the Unix command that translates characters. In version 1, tr(lines: Array[String], fromChar: String, toChar: String): String replaces every occurrence of fromChar with toChar in each line and returns the lines joined by \n.

    Both characters are single ASCII characters, taken literally: no escapes and no ranges. Upper and lower case are different characters. A line may be empty, and it may not contain fromChar at all. With ["banana", "apple"], fromChar = "a" and toChar = "X", the answer is "bXnXnX\nXpple".

    Approach

    Each line can be translated on its own, so the plan is a loop: translate a line, collect the result, and join everything at the end. The translation itself needs no loop over characters, because String.replace already replaces every occurrence of one piece of text with another.

    Note that fromChar and toChar are declared as String, not Char. That suits replace, which takes two strings in this form.

    You could also walk through each line character by character, build a new string and swap the matching characters yourself. That works, but it is more code for the same effect. For a single pair of characters, one call to replace is the simplest correct answer.

    Step by step

    1. Create result, an empty scala.collection.mutable.ArrayBuffer[String], in a val. It is a list that grows, and since you only add to it, val is enough.
    2. Write a for loop with line <- lines. Here line is a whole line of text, not a single character.
    3. Inside the loop, append line.replace(fromChar, toChar) to result with +=.
    4. After the loop, return result.mkString("\n"). The separator goes only between lines, so the output has no newline at the end.

    The solution in Scala

    class Solution {
        def tr(lines: Array[String], fromChar: String, toChar: String): String = {
            val result = scala.collection.mutable.ArrayBuffer[String]()
            for (line <- lines) {
                result += line.replace(fromChar, toChar)
            }
            return result.mkString("\n")
        }
    }
    

    Details worth knowing:

    • replace changes every occurrence, not only the first, and it returns a new string. Strings can't be modified in place, so after val t = line.replace("a", "X") with line = "banana", line is still banana and t is bXnXnX.
    • replace takes its arguments literally. The call "a.b.c".replace(".", "-") gives a-b-c. The similar method replaceAll treats its first argument as a regular expression, where . means "any character": "a.b.c".replaceAll(".", "-") gives -----. Since this lesson takes characters literally, replace is the right one.
    • Matching is case-sensitive: replacing "a" in "Apple" leaves the capital A alone.
    • The for (line <- lines) form loops over the elements themselves, with no index to manage.

    Complexity

    If the lines have a total of N characters, the work is O(N): replace scans each line once, and mkString copies each once. The buffer and the final string need O(N) space.

    Edge cases and common mistakes

    • Lines without the character. replace returns the line unchanged, so ["hello"] with "z" and "y" gives "hello".
    • Empty lines. They stay empty: ["", "abc", ""] with "a" and "z" gives "\nzbc\n", with the empty lines kept at both ends.
    • Case. ["Apple", "apple"] with "a" and "X" gives "Apple\nXpple".
    • The regex trap. replaceAll with a special character such as . gives surprising results, as shown above.
    • Joining inside the loop. Adding a "\n" after every line leaves a newline at the end. mkString avoids that.
    • Empty array. The result is "".

    Testing

    Inputs worth trying in the editor above, with the result of this solution and the newline shown as \n:

    linesfromChar, toCharresult
    ["banana", "apple"]"a", "X""bXnXnX\nXpple"
    ["a.b.c", "x"]".", "-""a-b-c\nx"
    ["Apple", "apple"]"a", "X""Apple\nXpple"
    ["", "abc", ""]"a", "z""\nzbc\n"
    []"a", "b"""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free