The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.
A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.
Function signature:
fn concat_cat(all_lines: Vec<Vec<String>>) -> String
Example:
Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]] Output: "hello\nworld\nfoo\nbar\nbaz" When printed: hello world foo bar baz
Collect every line into a flat
Vec<String> with a nested loop, preserving order. Then join the pieces with "\n".
A
Vec<String> has a built-in join, so once the lines are flattened you can stitch them together directly:
let mut flat: Vec<String> = Vec::new();
for file_lines in all_lines {
for line in file_lines {
flat.push(line);
}
}
flat.join("\n")
The full solution:
impl Solution {
fn concat_cat(all_lines: Vec<Vec<String>>) -> String {
let mut flat: Vec<String> = Vec::new();
for file_lines in all_lines {
for line in file_lines {
flat.push(line);
}
}
flat.join("\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
