Start learning free

LESSON 382 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v3 — Invert Match in C++

Practice

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

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

Example:

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

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Flip the condition from grep v1: keep lines where line.find(pattern) == string::npos.

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

STEP 1 OF 8
    Ctrl + Enter to check

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