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:
func tr(_ lines: [String], _ fromChar: String, _ toChar: String) -> String
Example:
Input: lines = ["banana", "apple"], fromChar = "a", toChar = "X" Output: "bXnXnX\nXpple" When printed: bXnXnX Xpple
Swift's
String.replacingOccurrences(of:with:) swaps EVERY occurrence. Apply it to each line and accumulate.
The full solution:
class Solution {
func tr(_ lines: [String], _ fromChar: String, _ toChar: String) -> String {
var result = [String]()
for line in lines {
result.append(line.replacingOccurrences(of: fromChar, with: toChar))
}
return result.joined(separator: "\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
