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: from_char and to_char 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 from_char at all.
Function signature:
fn tr(lines: Vec<String>, from_char: String, to_char: String) -> String
Example:
Input: lines = ["banana", "apple"], from_char = "a", to_char = "X" Output: "bXnXnX\nXpple" When printed: bXnXnX Xpple
Rust's
str::replace swaps EVERY occurrence and returns a new String. Collect the translated lines into a Vec<String> and join them with result.join("\n").
The full solution:
impl Solution {
fn tr(lines: Vec<String>, from_char: String, to_char: String) -> String {
let mut result: Vec<String> = Vec::new();
for line in &lines {
result.push(line.replace(&from_char, &to_char));
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
