Start learning free

LESSON 14 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool grep v2 in C++: Case-Insensitive Match (-i) with a toLower Helper

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:

string grepCaseInsensitive(vector<string> lines, string pattern)

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.


Write a small toLower helper that walks the string and lowercases each character with tolower(). Use it on both the pattern (once) and each line.

string toLower(string s) {
    for (int i = 0; i < s.size(); i++) {
        s[i] = tolower(s[i]);
    }
    return s;
}


The full solution:
class Solution {
public:
    string toLower(string s) {
        for (int i = 0; i < s.size(); i++) {
            s[i] = tolower(s[i]);
        }
        return s;
    }
    string grepCaseInsensitive(vector<string> lines, string pattern) {
        string result;
        bool first = true;
        string lowerPattern = toLower(pattern);
        for (int i = 0; i < lines.size(); i++) {
            if (toLower(lines[i]).find(lowerPattern) != string::npos) {
                if (!first) result += "\n";
                result += lines[i];
                first = false;
            }
        }
        return result;
    }
};

STEP 1 OF 9
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in C++, explained

    Problem overview

    This is the -i flag of grep. The function grepCaseInsensitive takes lines, a vector<string>, and a pattern, and returns the lines that contain the pattern as a substring while ignoring letter case. The matching lines come back joined by newlines, unchanged, with their original capitals. If no line matches, the result is the empty string. The lines contain only ASCII characters.

    With pattern = "ERR" and lines = ["Error: 1", "ok"] the result is "Error: 1". The pattern is in capitals and the line has Err, but they match once case is ignored, and the line is returned as it was written.

    Approach: compare lowercase copies, keep the original

    The previous version tested each line with find. To ignore case there is no need for a new search: make both sides the same case first. If the pattern and the line are both lowercase, ERR finds Error, and every other capitalization works as well.

    Two details matter. First, the lowercase pattern is made once, before the loop, because it is the same for every line. Second, the lowercase line is only a temporary copy used for the test. What goes into the result is the original lines[i], since the statement asks for the lines with their original casing.

    The starter code provides the helper toLower. It takes a string by value, which means it receives its own copy, replaces every character with its lowercase form using tolower, and returns the copy. The caller's string is never changed.

    Step by step

    1. Create an empty string named result for the matching lines.
    2. Create bool first = true, which remembers that no line has been added yet.
    3. Create lowerPattern with toLower(pattern). Doing it before the loop converts the pattern once, not once per line.
    4. Loop over the lines by position with i from 0 while i < lines.size().
    5. Test the lowercase line: toLower(lines[i]).find(lowerPattern) != string::npos. Both sides are lowercase, and find gives string::npos when there is no match.
    6. Add the separator with if (!first) result += "\n";, so the newline only goes between lines.
    7. Append the original lines[i] to result, not the lowercase copy.
    8. Set first to false.
    9. Return result after the loop. It is empty when nothing matched.

    The solution in C++

    class Solution {
    public:
        string toLower(string s) {
            for (int i = 0; i < s.size(); i++) {
                s[i] = tolower(s[i]);
            }
            return s;
        }
        string grepCaseInsensitive(vector<string> lines, string pattern) {
            string result;
            bool first = true;
            string lowerPattern = toLower(pattern);
            for (int i = 0; i < lines.size(); i++) {
                if (toLower(lines[i]).find(lowerPattern) != string::npos) {
                    if (!first) result += "\n";
                    result += lines[i];
                    first = false;
                }
            }
            return result;
        }
    };
    

    The C++ details worth a closer look:

    • tolower and its header. tolower comes from <cctype>, already available in the lesson. It converts an uppercase letter to lowercase and leaves every other character alone, so digits, spaces and punctuation pass through.
    • Why ASCII only. tolower expects a value that fits in an unsigned char (or EOF). A plain char holding a byte of a non-ASCII character can be negative, and passing that is undefined behaviour. With ASCII text every value is in range, which is why the lesson restricts the input.
    • Passing by value is what protects the input. Inside toLower, s[i] = tolower(s[i]) changes the copy. The pattern and the lines in the caller stay untouched, and that is what lets the function return the original text.
    • A temporary in the condition. toLower(lines[i]) creates a new string that lives until the end of the test. It is not stored anywhere, and find works on it directly.
    • Member functions on a call result. You can call .find(...) on the value that toLower returns, just as you would on a variable.

    Complexity

    Time. Each line is lowercased in time proportional to its length, and then searched. With a pattern of length m, a plain substring search of a line of length n can take up to about n * m comparisons in the worst case. Lowercasing the pattern once adds only O(m).

    Space: O(total length). The result holds copies of the matching lines, and the by-value parameters copy the input. The temporary lowercase line is as long as the longest line.

    Edge cases and common mistakes

    • Mixed case on both sides. ["Error: 1", "ok", "eRRor"] with "err" gives "Error: 1\neRRor". Both lines are returned exactly as written.
    • No match. ["ok", "fine"] with "ERR" gives "".
    • Returning the lowercase text. Appending toLower(lines[i]) to the result changes the output to lowercase. The test uses the copy; the result takes the original.
    • Lowercasing only one side. If only the line is lowercased, a pattern such as "ERR" can never match, because the line has no capitals left.
    • Converting the pattern inside the loop. It works, but it repeats the same conversion for every line.
    • Changing lines in place. The helper takes its argument by value for this reason. Writing a version that edits lines[i] would change the text that has to be returned in its original form.

    Testing

    • ["Error: 1", "ok"] with "ERR" gives "Error: 1".
    • ["Error: 1", "ok", "eRRor"] with "err" gives "Error: 1\neRRor".
    • ["WARNING: disk", "Warning", "ok"] with "warning" gives "WARNING: disk\nWarning".
    • ["ok", "fine"] with "ERR" gives "".
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free