Start learning free

LESSON 385 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v1 — Substring Match in Rust

Practice

Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).

Function signature:

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

Example:

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

Output: "error: foo\nanother error"

When printed:
error: foo
another error

If no lines match, return the empty string "".

Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.


Iterate over the lines, keep the ones where line.contains(&pattern) is true, then return result.join("\n").

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

STEP 1 OF 5
    Ctrl + Enter to check

    Grep V1 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