Start learning free

LESSON 13 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool grep v1 in C++: Substring Match with string::find

Practice Read the full explanation

Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).

Function signature:

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

Example:

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

Output: "error: foo\nanother error"

When printed:
error: foo
another error

If no lines match, return the empty string "".

Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.


Use line.find(pattern) != string::npos to test for substring presence. Track a first flag so you only insert "\n" between matches.

The full solution:
class Solution {
public:
    string grep(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 V1 in C++, explained

    Problem overview

    The function grep takes a vector<string> named lines and a string named pattern. It returns every line that contains pattern as a substring, in their original order, joined by newline characters. The match is case-sensitive, and the pattern is plain text: characters such as . and * mean nothing special. If no line matches, the function returns the empty string.

    In the example, pattern = "err" and the lines are ["error: foo", "warning", "another error", "ok"]. Lines 1 and 3 contain err, so the result is "error: foo\nanother error".

    Approach: test each line, glue the matches

    The work has two parts: deciding whether a line matches, and joining the matching lines with newlines between them but not after the last one.

    For the first part, string::find searches a string for a substring and returns the position of the first match. When there is no match it returns the special value string::npos. So a line contains the pattern exactly when lines[i].find(pattern) != string::npos. Comparing with npos is the correct test, because a match at the very start has position 0.

    For the second part, the function builds the result one piece at a time. A bool flag named first remembers whether any line has been added yet. The first line goes in without a newline in front, and every later line gets one. This way the separator only ever sits between two lines.

    Step by step

    1. Create an empty string named result. The matching lines are appended to it.
    2. Create bool first = true. It means no line has been added yet.
    3. Loop over the lines by position with i from 0 while i < lines.size().
    4. Test the line with lines[i].find(pattern) != string::npos. Everything else happens inside this if, so non-matching lines are skipped.
    5. Add the separator with if (!first) result += "\n";. For the very first match nothing is added.
    6. Append the line with result += lines[i].
    7. Set first to false so later matches get their newline.
    8. Return result after the loop. If nothing matched, result was never touched and is still the empty string the statement asks for.

    The solution in C++

    class Solution {
    public:
        string grep(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:

    • find returns a position, not a yes or no. The type is size_t, an unsigned integer, and npos is the largest value of that type. That is why the test compares with string::npos and not with a number such as -1 written by hand.
    • The test is on the whole line. A find result greater than 0 would miss a pattern at the start of a line, where the position is 0.
    • Why a flag and not result.empty(). Checking whether result is empty fails when a matching line is itself empty, as with an empty pattern, because the result is still empty after it is added. The flag records that a line was added, whatever its text.
    • The result is built in place. += appends to the end of a string. The two += operations in the loop do the whole joining; no separate join function is needed.
    • The empty pattern. find("") succeeds at position 0 in every string, so an empty pattern matches every line.

    Complexity

    Time. Let m be the pattern length and let the lines have lengths n1, n2 and so on. A plain substring search of a line of length n may need up to about n * m character comparisons in the worst case, so the total is bounded by the sum of those products. Appending the matching lines costs time proportional to their total length. For typical short patterns it behaves like a single pass over the text.

    Space: O(total length). The result holds a copy of every matching line, and the by-value parameters copy the input.

    Edge cases and common mistakes

    • No match. ["ok", "fine"] with pattern "err" gives "".
    • Case matters. ["Error", "error"] with pattern "err" gives "error": "Error" has a capital E, so it doesn't contain err.
    • Special characters are plain text. ["a.b", "abc"] with pattern "." gives "a.b". In a regular expression the dot would match every character, but here it only matches a dot.
    • Empty pattern. ["x", "y"] with pattern "" gives "x\ny", since every line contains the empty string.
    • Empty lines that match. ["", "a"] with pattern "" gives "\na": the empty line is kept, and the newline after it is still added.
    • Newline in the wrong place. Adding "\n" after every line leaves a trailing newline, which the expected result doesn't have.
    • Matching only at the start. Using find(pattern) == 0 selects lines that begin with the pattern, not lines that contain it. ["cat food", "the cat"] with pattern "cat" must return both.

    Testing

    • ["error: foo", "warning", "another error", "ok"] with "err" gives "error: foo\nanother error".
    • ["cat food", "the cat"] with "cat" gives "cat food\nthe cat".
    • ["ok", "fine"] with "err" gives "".
    • ["a.b", "abc"] with "." gives "a.b".
    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