Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count occurrences of a word in string | Set 2 (Using Regular Expressions)

  • Last Updated : 16 Jun, 2021

Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression.


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: str = “peter parker picked a peck of pickled peppers”, w = “peck”
Output: 1
Explanation: There is only one occurrence of the word “peck” in the given string. Therefore, the output is 1.

Input: str = “How much wood would a woodchuck chuck if a woodchuck could chuck wood ?”, w = “wood”
Output: 2
Explanation: There are only two occurrences of the word “wood” in the given string. 
Therefore, the output is 2.

Input: str = “She sells seashells by the seashore”, w = “sea”
Output: 0
Explanation: There is no occurrence of the word “sea” in the given string. Therefore, the output is 0.

Approach: The required regular expression to find the required count of string w in the given string is “\\bw\\b”, where \b is a word boundary.

Follow the steps to solve the problem

  • Traverse the string, match the regex with the string str using regex_iterator(). Simultaneously, update number of matches. 
  • Print the total number of matches obtained in the above step.

    Below is the implementation of the above approach :


    // C++ program for the above approach
    #include <iostream>
    #include <regex>
    using namespace std;
    // Function to count total occurrences
    // of word "w" in string "str"
    void countOccurrences(string str, string w)
        // Get the regex to be checked
        string regexPattern = "\\b" + w + "\\b";
        const regex pattern(regexPattern);
        // Variable to count total
        // occurrences of the given word
        int count = 0;
        auto it
            = sregex_iterator(str.begin(), str.end(), pattern);
        for (it; it != sregex_iterator(); it++) {
            // Increment count
        // Print the occurrences of the word
        cout << count << endl;
    // Driver Code
    int main()
        // Input
        string str
            = "peter parker picked a peck of pickled peppers";
        string w = "peck";
        countOccurrences(str, w);
        return 0;

    Time Complexity : O(N)
    Auxiliary Space : O(N)

    My Personal Notes arrow_drop_up
  • Recommended Articles
    Page :

    Start Your Coding Journey Now!