Start learning free

LESSON 387 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v3 — Invert Match in Rust

Practice

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

fn grep_invert(lines: Vec<String>, pattern: String) -> String

Example:

Input:
pattern = "err"
lines = ["error", "ok", "another error", "fine"]

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Same as grep v1 but flip the condition: keep the lines where !line.contains(pattern.as_str()) is true, then return result.join("\n").

The full solution:
impl Solution {
    fn grep_invert(lines: Vec<String>, pattern: String) -> String {
        let mut result: Vec<String> = Vec::new();
        for line in &lines {
            if !line.contains(pattern.as_str()) {
                result.push(line.clone());
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    Grep V3 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free