Start learning free

LESSON 16 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool grep v4 in C++: Whole Word Match (-w) with compare and isWordChar

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Grep V4 in C++, explained

    Problem overview

    This is the -w flag of grep. The function grepWord takes lines, a vector<string>, and a pattern, a single word made of letters, digits and underscores. It returns the lines that contain the pattern as a whole word, joined by newlines. The characters right before and right after the match must not be word characters. The match is case-sensitive, the lines are ASCII, and the result is empty when nothing matches.

    With pattern = "cat" and lines ["cat sat", "concat", "the cat", "category"] the result is "cat sat\nthe cat". In "concat" the match is preceded by the word character n, and in "category" it is followed by e. A line can contain the pattern several times and is selected if at least one occurrence is a whole word, so "concat cat" is selected because of its second cat.

    Approach: try every position and check both neighbours

    Plain find isn't enough here. It reports the first place where the pattern occurs, and that occurrence may be the wrong one: in "concat cat" the first cat is inside a word, and only the second counts. So the function scans the line itself, one start position at a time, and checks each candidate.

    At a position pos, the candidate is the m characters of the line starting there, where m is the pattern length. If they equal the pattern, the function looks at the character before (pos - 1) and the character after (pos + m). A boundary is fine when it lies outside the line, or when the neighbour is not a word character. If both sides are fine, the line is selected and the scan stops, because one whole-word match is enough. If not, the scan moves on by one position, so overlapping candidates are not skipped.

    The starter code gives the helper isWordChar, which is true for letters, digits and the underscore. The result is built as in the earlier versions, with a first flag controlling the newline separator.

    Step by step

    1. Create result and first. They work as in version 1: an empty string for the selected lines and a flag meaning that none has been added.
    2. Store the pattern length in m with pattern.size(). It locates the character just after a match.
    3. Loop over the lines by position with i from 0 while i < lines.size().
    4. Take a const string& named line that refers to lines[i]. It is a second name for the same string: no copy, and a shorter name.
    5. Store the line length in n. It marks the right edge.
    6. Create bool matched = false. Each line starts as not matched.
    7. Create int pos = 0, the start position of the next candidate.
    8. Loop while pos + m <= n. A candidate must fit inside the line, so starting later than n - m is pointless.
    9. Compare the candidate with line.compare(pos, m, pattern) == 0. The call compares the m characters from pos with the pattern and returns 0 when they are equal.
    10. Compute leftOk: true when pos == 0, or when line[pos - 1] is not a word character.
    11. Compute rightOk: true when the match ends at the end of the line (pos + m == n), or when line[pos + m] is not a word character.
    12. Accept the candidate only if both are true. Then set matched to true and break.
    13. Move to the next position with pos++, after the compare check and still inside the while. Without it the loop would test the same position forever.
    14. After the scan, add the line if matched: a newline when first is false, then the line, then first = false.
    15. Return result after the outer loop.

    The solution in C++

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

    The C++ details worth a closer look:

    • Short-circuit evaluation protects the indexing. In (pos == 0) || !isWordChar(line[pos - 1]), the right side runs only when pos is above 0, so line[-1] is never evaluated. In the same way, (pos + m == n) || ... skips the read of line[pos + m] when that index would be one past the end of the line. Swapping the two operands would break both guards.
    • compare(pos, m, pattern). It compares a substring of line with pattern without creating a temporary string. It returns 0 for equal text, so the test is == 0. The while condition guarantees that pos + m never exceeds the line length, so the call stays inside the string.
    • const string&. A reference to a const string avoids copying the line, and const promises that this code won't change it.
    • Characters are compared with ranges. c >= 'a' && c <= 'z' works for ASCII because the letters and the digits are contiguous in the character table. The underscore is handled with a separate comparison.
    • int positions. size() returns an unsigned value. Storing the lengths in int variables means that expressions such as pos + m <= n and pos - 1 follow ordinary signed arithmetic, with no wrap-around at 0.

    Complexity

    Time. For a line of length n and a pattern of length m, there are at most n - m + 1 candidate positions, and each compare may look at up to m characters. The cost per line is therefore at most about n * m comparisons, and it is much less for most inputs because a comparison stops at the first different character. Appending the selected lines is proportional to their total length.

    Space: O(total length). The result holds copies of the selected lines, and the by-value parameters copy the input. The scan itself uses a few integers and no copy of the line.

    Edge cases and common mistakes

    • Pattern inside a longer word. ["cat", "dog"] with "cats" gives "", and ["cat sat", "concat", "the cat", "category"] with "cat" keeps only the first and third lines.
    • Several occurrences. ["concat cat"] with "cat" returns the line. The first occurrence fails the left test, the scan continues by one position, and the second occurrence passes.
    • The underscore is a word character. ["cat_x", "a cat, b", "cat", "x-cat-y"] with "cat" gives "a cat, b\ncat\nx-cat-y". "cat_x" is rejected, while a comma or a hyphen next to the match counts as a boundary.
    • Match at the start or end of the line. ["cat", "the cat", "cats"] with "cat" gives "cat\nthe cat". A line edge counts as a boundary, so the whole line "cat" is a whole word.
    • Case matters. ["Cat", "cat"] with "cat" gives "cat".
    • Stepping by m instead of 1. Skipping ahead by the pattern length after a failed candidate can jump over the start of a later match. Overlapping starts are tested only when the position moves by one.
    • Using the first find result only. That checks one occurrence, so "concat cat" would be rejected.
    • Forgetting break. The result is still correct, since matched stays true, but the scan keeps going after the answer is known.
    • Empty list. An empty vector gives "", because the loop doesn't run.

    Testing

    • ["cat sat", "concat", "the cat", "category"] with "cat" gives "cat sat\nthe cat".
    • ["concat cat"] with "cat" gives "concat cat".
    • ["catcat cat"] with "cat" gives "catcat cat".
    • ["cat_x", "a cat, b", "cat", "x-cat-y"] with "cat" gives "a cat, b\ncat\nx-cat-y".
    • ["hi"] with "hi there" 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