Start learning free

LESSON 381 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v2 — Case-Insensitive Match in C++

Practice

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

    Grep V2 in C++

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