Start learning free

LESSON 25 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in TypeScript: Swapping One Character with split and join

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:

tr(lines: string[], fromChar: string, toChar: string): string

Example:

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

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

In TypeScript, passing a string to replace only swaps the first occurrence. To replace ALL of them with a literal char, the easiest trick is line.split(fromChar).join(toChar).

The full solution:
class Solution {
    tr(lines: string[], fromChar: string, toChar: string): string {
        let result: string[] = [];
        for (let i = 0; i < lines.length; i++) {
            result.push(lines[i].split(fromChar).join(toChar));
        }
        return result.join("\n");
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in TypeScript, explained

    Problem overview

    This is the first version of the tr project, a tiny version of the Unix tr command. The method tr(lines: string[], fromChar: string, toChar: string) receives an array of lines and two single ASCII characters. It replaces every fromChar with toChar in every line and returns the lines joined by \n.

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

    Approach: replace in every line, collect, join

    The work splits into two parts: fix one line, then do it for all the lines. For one line you need to replace every occurrence, not just the first one. The obvious tool, replace, does not do that when it is given a string: "banana".replace("a", "X") gives "bXnana", only the first a changed.

    The lesson uses a pair of calls instead. line.split(fromChar) cuts the line into pieces at every fromChar, and the character itself disappears. .join(toChar) glues the pieces back with toChar between each two. For "banana" the pieces are ["b", "n", "n", ""], and joining them with "X" gives "bXnXnX". The empty piece at the end appears because the line ends with a, and it is what puts the last X in place.

    A bonus of this approach: when the argument is a string, split treats it as plain text, not as a pattern. Splitting "a.b.c" on "." works as expected, whereas a regular expression would treat the dot as "any character". That suits the "taken literally" rule.

    Step by step

    1. Create result, an empty string[], with let. The swapped lines go into it.
    2. Loop over the lines with i from 0 while i < lines.length.
    3. Push the swapped line: lines[i].split(fromChar).join(toChar).
    4. After the loop, return result.join("\n"). The separator goes only between lines, so there is no newline after the last one.

    The solution in TypeScript

    class Solution {
        tr(lines: string[], fromChar: string, toChar: string): string {
            let result: string[] = [];
            for (let i = 0; i < lines.length; i++) {
                result.push(lines[i].split(fromChar).join(toChar));
            }
            return result.join("\n");
        }
    }
    

    Language details

    • Strings are immutable in JavaScript and TypeScript, so split and join return new values and never change lines[i]. The caller's array stays as it was.
    • TypeScript has no separate character type: fromChar and toChar are strings of length one, which is why the signature uses string.
    • split and join each take a separator. The same character plays two roles here: the first call removes it, the second inserts another.

    Complexity

    Each line is scanned once by split and once by join, so the time is proportional to the total number of characters in all the lines, O(N). The extra space is the result array and the pieces for one line at a time, again O(N) in the worst case.

    Edge cases and common mistakes

    • Using replace. With a string argument it changes only the first match. "banana".replace("a", "X") gives "bXnana", while "banana".split("a").join("X") gives "bXnXnX".
    • Case. fromChar = "b" does not touch the capital B: ["Banana"] becomes "Banana", and with "B" it becomes "Xanana".
    • Special characters. ["a.b.c", "xyz", ""] with "." and "-" gives "a-b-c\nxyz\n": lines without the character and empty lines pass through, and the empty last line leaves a newline at the end of the text.
    • Trailing newline. Joining with "\n" never adds a newline after the last line; the only one at the end above is the separator before an empty final line.

    Testing

    InputResult
    ["banana", "apple"], "a", "X""bXnXnX\nXpple"
    ["a.b.c", "xyz", ""], ".", "-""a-b-c\nxyz\n"
    ["Banana"], "b", "X""Banana"
    ["Banana"], "B", "X""Xanana"
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free