Start learning free

LESSON 25 OF 68 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in Java: Swap One Character with String.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:

public String tr(List<String> lines, String fromChar, String toChar)

Example:

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

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

Java's String.replace(CharSequence, CharSequence) swaps EVERY occurrence (unlike replaceFirst). Apply it to each line and accumulate.

The full solution:
class Solution {
    public String tr(List<String> lines, String fromChar, String toChar) {
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            result.add(line.replace(fromChar, toChar));
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in Java, explained

    Problem overview

    The first version of the tr tool swaps one character for another. The method tr(List<String> lines, String fromChar, String toChar) replaces every occurrence of fromChar with toChar in each line, then returns the lines joined by \n.

    Both arguments are single ASCII characters, taken literally. There are no escapes and no ranges, and upper and lower case are different characters. A line may be empty, or may not contain fromChar at all.

    For ["banana", "apple"], fromChar = "a" and toChar = "X", the answer is "bXnXnX\nXpple". Printed, that is two lines: bXnXnX and Xpple.

    Notice that fromChar and toChar are String parameters, not char. The signature says one character each, but the type is String, and the code works with that.

    Approach: translate each line, collect, join

    The work for one line is a single method call, replace, so the method needs a loop that does it for each line and a place to collect the results:

    1. create an empty list for the translated lines;
    2. for each input line, add its translated copy to that list;
    3. join the list with newlines.

    Strings in Java are immutable. line.replace(...) never changes line: it returns a new string, and the original stays as it was. That is why the results go into a new list rather than back into lines.

    A for-each loop fits here because the position of a line doesn't matter, only the line itself. This version hands the whole line to replace and never looks at its characters one by one.

    Step by step

    1. Create result, a List<String> set to a new, empty ArrayList. Unlike an array, a list grows as you add, which suits lines handled one at a time.
    2. Loop over the lines with a for-each loop that names each element line. It needs no index.
    3. Translate and add. Inside the loop, line.replace(fromChar, toChar) gives the translated line, and result.add(...) stores it.
    4. Join after the loop. String.join("\n", result) puts a newline between each two lines, with none after the last one. This line sits outside the loop, because it runs once.

    The solution in Java

    class Solution {
        public String tr(List<String> lines, String fromChar, String toChar) {
            List<String> result = new ArrayList<>();
            for (String line : lines) {
                result.add(line.replace(fromChar, toChar));
            }
            return String.join("\n", result);
        }
    }
    

    Details worth knowing:

    • replace changes every occurrence. It doesn't stop at the first one. For "banana" with "a" and "X" the result is bXnXnX.
    • replace is literal. It takes plain text, not a pattern. "a.b".replace(".", "-") gives a-b. replaceAll, by contrast, takes a regular expression, where . matches any character: "a.b".replaceAll(".", "-") gives ---. For a tool that takes characters literally, use replace.
    • replace also has a char version. line.replace('a', 'X') gives the same result, but the parameters of this method are strings, so the string version fits.
    • Imports. List and ArrayList are in java.util.

    Complexity

    Time: O(t), where t is the total number of characters in all lines. replace scans each line once, and joining copies the text once more.

    Space: O(t). The translated lines and the joined result hold a copy of the text, and the input lines are left untouched.

    Edge cases and common mistakes

    • Case matters. With fromChar = "A", the lines ["banana", "apple"] stay unchanged: "banana\napple".
    • Characters that look special. ["a.b.c"] with "." and "-" gives "a-b-c". This works because replace isn't a pattern.
    • Same character on both sides. ["one"] with "o" and "o" gives "one".
    • Empty list. [] gives "".
    • Ignoring the return value. Writing line.replace(fromChar, toChar); on its own line does nothing useful, because the new string is thrown away.

    Testing

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