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");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
