Start learning free

LESSON 380 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v1 — Substring Match in C++

Practice

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

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