Start learning free

LESSON 25 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr in Kotlin: Swapping One Character with replace

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:

fun tr(lines: List<String>, fromChar: String, toChar: String): String

Example:

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

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

Kotlin's String.replace(oldValue, newValue) swaps EVERY occurrence. Apply it to each line and accumulate.

The full solution:
class Solution {
    fun tr(lines: List<String>, fromChar: String, toChar: String): String {
        val result = mutableListOf<String>()
        for (line in lines) {
            result.add(line.replace(fromChar, toChar))
        }
        return result.joinToString("\n")
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in Kotlin, explained

    Problem overview

    The tr project rebuilds the Unix command that translates characters. In this first version, tr(lines: List<String>, fromChar: String, toChar: String): String receives a list of lines and two single-character strings. In every line, each fromChar becomes toChar, and the translated lines are returned joined with \n.

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

    Approach

    Each line can be translated on its own, because a replacement in one line never affects another. So the function walks over the lines, translates each one with a string method that replaces text, collects the results and joins them at the end.

    Kotlin's String.replace(oldValue, newValue) does the translation in one call. It looks for every occurrence of the first string and puts the second in its place.

    Step by step

    1. Prepare the output list. result is a val holding mutableListOf<String>(). The translated lines are added to it one at a time.
    2. Loop over the lines. for (line in lines) hands out one whole line per round, not one character.
    3. Translate and store. Inside the loop, line.replace(fromChar, toChar) builds the translated line, and result.add stores it.
    4. Join after the loop. result.joinToString("\n") runs once, outside the braces. The separator goes between lines only, so the string doesn't end with a newline.

    The solution in Kotlin

    class Solution {
        fun tr(lines: List<String>, fromChar: String, toChar: String): String {
            val result = mutableListOf<String>()
            for (line in lines) {
                result.add(line.replace(fromChar, toChar))
            }
            return result.joinToString("\n")
        }
    }
    

    Kotlin details in this code

    • replace changes every occurrence. It doesn't stop after the first match, as "banana" turning into "bXnXnX" shows.
    • Strings are immutable. replace returns a new string and the original line is untouched. That is why the result of the call is passed to result.add instead of being thrown away.
    • The parameters are String, not Char. The lesson passes the characters as one-character strings, so the replace(String, String) overload is used. Kotlin also has replace(Char, Char), but it would need Char arguments, such as 'a' in single quotes.
    • The match is case-sensitive. By default replace treats "a" and "A" as different, which matches the lesson. With "a" and "X", the line "Banana" becomes "BXnXnX": the capital B is not touched, and neither would a capital A be.
    • The text is searched literally. replace(String, String) doesn't treat its first argument as a pattern, so "." means a dot, not "any character". Translating "." to "-" in "a.b.c" gives "a-b-c".

    Complexity

    Each line is scanned once, so the time is proportional to the total number of characters in all the lines. The extra space is the result list and the final string, the same size as the input.

    Edge cases and common mistakes

    • An empty line has nothing to replace and stays empty, so it appears in the output as an empty line. For ["Banana", "", "cherry"] with "a" and "X" the result is BXnXnX, an empty line, and cherry.
    • A line without fromChar is returned as it was: "cherry" above.
    • Ignoring the return value. Calling line.replace(fromChar, toChar) without using the result does nothing useful, because the line can't change.
    • A trailing newline. Don't add "\n" after each line yourself: joinToString("\n") already puts it between lines, and the lesson's output has none at the end.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free