Now build the -A flag of the cat tool, as a new function. It makes whitespace visible: every tab character (\t) is replaced by the two characters ^I and every line ends with a literal $ marker (so trailing spaces become obvious). Lines are then joined with newlines.
Note: real cat -A also shows other control characters (such as ^M) and non-ASCII bytes; this version only handles tabs and line ends, like cat -T -E. A blank line becomes just $, and an empty list gives an empty string.
Function signature:
fn show_all_cat(lines: Vec<String>) -> String
Example:
Input: lines = ["hello\tworld", "foo"] Output: "hello^Iworld$\nfoo$" When printed: hello^Iworld$ foo$
Another example (a blank line, trailing spaces):
Input: lines = ["a\t", "", "x "] Output: "a^I$\n$\nx $" When printed: a^I$ $ x $
Walk each line character by character with
line.chars(). When you see a '\t', add "^I" to the transformed line; otherwise push the character itself. After the inner loop, add "$".
Inner transformation:
let mut transformed = String::new();
for c in line.chars() {
if c == '\t' {
transformed += "^I";
} else {
transformed.push(c);
}
}
result.push_str(&(transformed + "$"));
The full solution:
impl Solution {
fn show_all_cat(lines: Vec<String>) -> String {
let mut result = String::new();
for i in 0..lines.len() {
if i > 0 {
result += "\n";
}
let line = &lines[i];
let mut transformed = String::new();
for c in line.chars() {
if c == '\t' {
transformed += "^I";
} else {
transformed.push(c);
}
}
result.push_str(&(transformed + "$"));
}
return result;
}
}
Free plan: 30 tutor messages. Premium is unlimited.
