Start learning free

LESSON 15 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool grep v3 in C++: Invert Match (-v) with string::npos

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Grep V3 in C++, explained

    Problem overview

    This is the -v flag of grep. The function grepInvert takes lines, a vector<string>, and a pattern, and returns the lines that do not contain the pattern as a substring. The test is case-sensitive. The remaining lines keep their original order and come back joined by newline characters. If every line contains the pattern, the result is the empty string.

    For pattern = "err" and lines = ["error", "ok", "another error", "fine"] the result is "ok\nfine": the first and third lines contain err, so they are dropped.

    Approach: flip the test

    Version 1 of this tool kept the lines where find found the pattern. Here the loop is the same and only the condition changes: keep a line when lines[i].find(pattern) equals string::npos, which is the value find returns when the pattern is absent.

    Everything else stays as before. A first flag decides whether a newline goes in front of a kept line, so newlines appear only between lines, never before the first or after the last.

    Think of the two versions as one function with a switch on the test. Which lines are kept depends only on the condition; how they are joined does not. That is why a tool like this one can grow flags without rewriting its loop.

    The empty pattern shows the idea clearly. Every line contains the empty string, so version 1 returns all lines and this version returns none. The two results always split the input into two complementary sets, and every line goes to exactly one of them.

    The same condition can be written as !(lines[i].find(pattern) != string::npos). That reads as "not contains" and gives identical results, but the direct comparison with == is shorter and easier to read. Whichever form you choose, make sure the negation applies to the whole test and not to the position that find returns: !lines[i].find(pattern) is true only when the match is at position 0, which is a different question altogether.

    Because the loop never changes, the function also stays correct for lines of any content, including empty lines: an empty line contains no pattern except the empty one, so it is kept for every non-empty pattern.

    Step by step

    1. Create an empty string named result for the lines that are kept.
    2. Create bool first = true, meaning no line has been added yet.
    3. Loop over the lines by position with i from 0 while i < lines.size().
    4. Keep the line only if the pattern is missing: lines[i].find(pattern) == string::npos.
    5. Add the separator with if (!first) result += "\n";.
    6. Append lines[i] to result. Only lines without the pattern get this far.
    7. Set first to false.
    8. Return result after the loop. If every line had the pattern, nothing was added, and result is still empty.

    The solution in C++

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

    The C++ details worth a closer look:

    • == against npos means "not found". find returns string::npos only when there is no match anywhere in the line. Any real position, including 0, means the pattern is present and the line must be dropped.
    • The condition is the whole change. Going from != to == turns "lines that match" into "lines that don't", and the rest of the function works for both.
    • The separator logic doesn't depend on the test. The flag records that a line was added, whatever the test was, so no newline appears before the first kept line.
    • Lines are copied unchanged. The function doesn't trim or alter them; a kept line appears in the result exactly as it was in the input.

    Complexity

    Time. Each line is searched once. With a pattern of length m, searching a line of length n may take up to about n * m comparisons in the worst case, and appending the kept lines costs time proportional to their total length.

    Space: O(total length). The result may hold copies of nearly every line, and the by-value parameters copy the input.

    Edge cases and common mistakes

    • Every line matches. ["error", "another error"] with "err" gives "".
    • Case matters. ["Error", "ok"] with "err" gives "Error\nok". "Error" has a capital E, so it does not contain err and is kept.
    • Empty pattern. ["a", "b"] with "" gives "", because every line contains the empty string and all lines are dropped.
    • Testing for a position of 0. Writing a condition such as find(pattern) < 0 doesn't work: the result is unsigned and never negative. Compare with string::npos.
    • Keeping the matching lines. Leaving != in place from version 1 returns the opposite set.
    • A stray newline. A newline written after every kept line leaves a trailing one that the expected result doesn't have.

    Testing

    • ["error", "ok", "another error", "fine"] with "err" gives "ok\nfine".
    • ["error", "another error"] with "err" gives "".
    • ["Error", "ok"] with "err" gives "Error\nok".
    • ["a", "b"] with "" 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