Start learning free

LESSON 14 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -i in Rust: Case-Insensitive Match with to_lowercase()

Practice Read the full explanation

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

STEP 1 OF 6
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in Rust, explained

    Problem overview

    This version adds the -i flag of grep. The function grep_case_insensitive takes a Vec<String> of lines and a pattern, and returns the lines that contain the pattern as a substring, ignoring letter case. The kept lines are joined with \n, and an empty string is returned when nothing matches.

    With pattern = "ERR" and lines = ["Error: 1", "ok"] the result is "Error: 1". The line matches because Err and ERR are the same up to case, and the line comes back with its original capitalization. The lines contain only ASCII characters.

    Approach: compare in one case, return the original

    The previous version used contains directly, and contains is case-sensitive. The usual trick for ignoring case is to bring both sides to the same case before comparing. Convert the pattern to lowercase, convert the line to lowercase, and check whether the lowercase line contains the lowercase pattern. Then "ERR" and "Error" both turn into "err" and "error", and the match is found.

    The conversion is only for the check. The lowercase copy of a line is thrown away right after the test, and the line that goes into the result is the original one. This is why the output keeps "Error: 1" with its capital E.

    The pattern doesn't change from line to line, so it is converted once before the loop. Lowercasing it inside the loop would give the same answers but redo the same work for every line.

    Step by step

    1. Create the result vector. A Vec<String> declared with let mut will hold the kept lines.
    2. Lowercase the pattern once. pattern.to_lowercase() returns a new String, stored in lower_pattern. The original pattern stays as it was.
    3. Loop over the lines by reference with for line in &lines.
    4. Test the lowercase line. line.to_lowercase().contains(&lower_pattern) lowercases the current line into a temporary string and asks whether it contains the lowercase pattern. Both sides are in the same case now, so ERR finds Error.
    5. Keep the original line. result.push(line.clone()) stores a copy of line, not of its lowercase version.
    6. Join and return. result.join("\n") puts a newline between lines, and gives "" for an empty result.

    The solution in Rust

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

    Rust details worth knowing:

    • to_lowercase() returns a new String. Strings in Rust can't be changed into lowercase in place with this method. It allocates a fresh String, so line itself is untouched. That is why the original line is still available to push.
    • A temporary in the condition. line.to_lowercase() creates a value that exists only for the duration of the if condition. You can call contains on it directly without naming it.
    • Unicode. to_lowercase() follows Unicode rules, not just ASCII, which is more than this lesson needs, since the input is ASCII. For ASCII text, to_ascii_lowercase() would work too.
    • &lower_pattern. As in the plain version, the & lends the string to contains so that it can be used again on the next line.

    Complexity

    Time: roughly O(m), where m is the total length of all lines. Each line is lowercased once, which is linear in its length, and then searched. Copying the kept lines and joining them is linear too.

    Space: O(k + L), where k is the total length of the kept lines and L is the length of the longest line, for its temporary lowercase copy.

    Edge cases and common mistakes

    • Lowercasing only one side. If the line is lowercased but the pattern is not, "ERR" would never match anything. Both sides must be converted.
    • Returning the lowercase line. The result must keep the original casing. With ["Error: 1", "ok", "eRRor", "fine"] and the pattern "err", the result is "Error: 1\neRRor", with each line as it was.
    • Mixed case in the pattern. "mIxEd" on ["MiXeD", "mixed"] keeps both lines: "MiXeD\nmixed".
    • No match. For the pattern "xyz" on ["Error: 1", "ok"], the result is "".
    • Empty list. The loop doesn't run and the result is the empty string.
    • Repeating work in the loop. Moving pattern.to_lowercase() inside the loop still passes the tests, but it converts the same pattern again for every line.

    Testing

    Inputs worth trying, with the results the function returns:

    • "ERR" on ["Error: 1", "ok"] gives "Error: 1".
    • "err" on ["Error: 1", "ok", "eRRor", "fine"] gives "Error: 1\neRRor".
    • "xyz" on ["Error: 1", "ok"] gives "".
    • "mIxEd" on ["MiXeD", "mixed"] gives "MiXeD\nmixed".
    • 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