Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).
Function signature:
fn grep_case_insensitive(lines: Vec<String>, pattern: String) -> String
Example:
Input: pattern = "ERR" lines = ["Error: 1", "ok"] Output: "Error: 1" When printed: Error: 1
The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.
Lowercase the pattern once with
to_lowercase(). For each line, check line.to_lowercase().contains(&lower_pattern) and push the ORIGINAL line on a hit.
The full solution:
impl Solution {
fn grep_case_insensitive(lines: Vec<String>, pattern: String) -> String {
let mut result: Vec<String> = Vec::new();
let lower_pattern = pattern.to_lowercase();
for line in &lines {
if line.to_lowercase().contains(&lower_pattern) {
result.push(line.clone());
}
}
return result.join("\n");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
