Start learning free

LESSON 13 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep in Rust: Filtering Lines with contains()

Practice Read the full explanation

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

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in Rust, explained

    Problem overview

    This is a small version of the Unix grep command. The function grep takes a Vec<String> of lines and a pattern, and returns every line that contains the pattern as a substring. The match is case-sensitive, and the kept lines are joined with \n into one String. If no line matches, the result is the empty string.

    With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], the result is "error: foo\nanother error". Printed, it shows two lines: error: foo and another error. The pattern is plain text. In the real tool, characters such as . and * have special meanings in a pattern; here they mean nothing special and are matched literally.

    Approach: test each line, keep the ones that pass

    This is a filter: look at every line, decide whether it matches, and collect the matches in their original order. Rust's str::contains does the deciding. It reports whether the given text appears anywhere inside the string, not just at its start, so "another error" matches "err" even though it doesn't begin with it.

    The kept lines go into a Vec<String>, and a single join("\n") at the end produces the output. Joining is better than appending "\n" after every line, because the separator belongs only between two lines. A manual loop that adds a newline each time leaves a stray newline at the end that the expected output doesn't have.

    Step by step

    1. Create an empty result vector. It has type Vec<String>, is made with Vec::new(), and needs let mut because every kept line changes it.
    2. Loop over the lines by reference. for line in &lines borrows the vector, so it still exists after the loop, and line is a &String on each pass.
    3. Test the line. line.contains(&pattern) is true when the pattern appears anywhere in the line. The & lends the pattern to contains instead of moving it, so it can be reused for the next line.
    4. Keep the line. Inside the if, result.push(line.clone()) adds a copy. The vector needs its own String, and line is only a borrowed reference.
    5. Join and return. result.join("\n") glues the kept lines with a newline between each two. With an empty result it returns the empty string, which is exactly what the problem asks for when nothing matched.

    The solution in Rust

    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");
        }
    }
    

    Rust details worth knowing:

    • Borrowing the pattern. contains accepts several kinds of pattern, such as a &str, a char or a closure. A &String works too. Passing pattern without the & would move the String into the first call and fail to compile on the second pass of the loop.
    • clone(). The loop only borrows the lines, and a Vec<String> can't hold borrowed references without extra lifetime annotations. clone() makes an owned copy, which costs an allocation per kept line.
    • join on a vector of strings. Vec<String> has a join method that takes the separator and returns a String. A vector with one item gives that item with no separator, and an empty vector gives "".
    • Explicit return. Ending the function with the bare expression result.join("\n") would work as well.

    Complexity

    Time: roughly O(m), where m is the total length of all lines. Every line is searched once, and the standard library's substring search is linear in the line's length plus the pattern's length. Copying the kept lines and joining them is linear in their total length.

    Space: O(k), where k is the total length of the kept lines, because the result holds copies of them.

    Edge cases and common mistakes

    • No matches. For pattern = "zzz" on the example lines, the function returns the empty string.
    • Case matters. With pattern = "Err", the example gives the empty string, because the lines contain a lowercase err only.
    • Special characters are plain text. With ["a.c", "abc", "a*c"] and the pattern "a.c", only "a.c" is returned. . doesn't match any character here.
    • Empty pattern. Every string contains the empty string, so an empty pattern keeps all lines. With ["a.c", "abc"] the result is "a.c\nabc".
    • Empty list. The loop doesn't run and the result is "".
    • Trailing newline. Joining puts the separator only between lines. Building the output by adding "\n" after each kept line would add an extra one at the end.
    • Checking only the start. starts_with is a different test. The problem wants the pattern anywhere in the line.

    Testing

    Inputs worth trying, with the results the function returns:

    • "err" on ["error: foo", "warning", "another error", "ok"] gives "error: foo\nanother error".
    • "zzz" on the same lines gives "".
    • "a.c" on ["a.c", "abc", "a*c"] gives "a.c".
    • "only" on ["only"] gives "only".
    • Any pattern on an empty vector gives "".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free