Start learning free

LESSON 383 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v4 — Whole Word Match in C++

Practice

Build the -w flag of the Unix grep command. Given a list of lines and a search pattern (a single word made of letters, digits, and underscores), return all lines that contain pattern as a WHOLE word — i.e. the characters immediately before and after the match must NOT be word characters (letters, digits, or underscores). The match is case-sensitive.

Return the matching lines joined by newline characters (\n).

Function signature:

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

Example:

Input:
pattern = "cat"
lines = ["cat sat", "concat", "the cat", "category"]

Output: "cat sat\nthe cat"

When printed:
cat sat
the cat

Notice that "concat" is rejected because cat is preceded by the word character n (con|cat), and "category" is rejected because cat is followed by the word character e.

A line may contain the pattern more than once. It is selected if at least one occurrence is a whole word: with pattern "cat", the line "concat cat" is selected because of its second cat. The lines contain only ASCII characters.

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


Don't reach for <regex> — write a simple manual scan. For each occurrence of pattern in line, check that the character to its LEFT and the character to its RIGHT are NOT word characters (or are the line edge).

Helper for word-char detection:
bool isWordChar(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
        || (c >= '0' && c <= '9') || c == '_';
}
Then walk the line with line.compare(pos, m, pattern) at every position; if it matches AND both edges are non-word, keep the line.

The full solution:
class Solution {
public:
    bool isWordChar(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
    }
    string grepWord(vector<string> lines, string pattern) {
        string result;
        bool first = true;
        int m = pattern.size();
        for (int i = 0; i < lines.size(); i++) {
            const string& line = lines[i];
            int n = line.size();
            bool matched = false;
            int pos = 0;
            while (pos + m <= n) {
                if (line.compare(pos, m, pattern) == 0) {
                    bool leftOk = (pos == 0) || !isWordChar(line[pos - 1]);
                    bool rightOk = (pos + m == n) || !isWordChar(line[pos + m]);
                    if (leftOk && rightOk) {
                        matched = true;
                        break;
                    }
                }
                pos++;
            }
            if (matched) {
                if (!first) result += "\n";
                result += line;
                first = false;
            }
        }
        return result;
    }
};

STEP 1 OF 21
    Ctrl + Enter to check

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