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.
Examples:
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
- Create the regular expression pattern for the word w
regex = “\\bw\\b”
- 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++
| // C++ program for the above approach#include <iostream>#include <regex>usingnamespacestd;// Function to count total occurrences// of word "w" in string "str"voidcountOccurrences(string str, string w){    // Get the regex to be checked    string regexPattern = "\\b"+ w + "\\b";    constregex pattern(regexPattern);    // Variable to count total    // occurrences of the given word    intcount = 0;    autoit        = sregex_iterator(str.begin(), str.end(), pattern);    for(it; it != sregex_iterator(); it++) {        // Increment count        count++;    }    // Print the occurrences of the word    cout << count << endl;    return;}// Driver Codeintmain(){    // Input    string str        = "peter parker picked a peck of pickled peppers";    string w = "peck";    countOccurrences(str, w);    return0;} | 
Java
| // Java program for the above approachimportjava.util.*;importjava.util.regex.*;classGFG {  // Function to count total occurrences  // of word "w" in String "str"  staticvoidcountOccurrences(String str, String w)   {        // Get the regex to be checked    String regexPattern = "\\b"+ w + "\\b";    Pattern pattern = Pattern.compile(regexPattern);        // Variable to count total    // occurrences of the given word    intcount = 0;    while(str.contains(w)) {      str = str.replace(w, "");      // Increment count      count++;    }    // Print the occurrences of the word    System.out.print(count + "\n");    return;  }  // Driver Code  publicstaticvoidmain(String[] args)  {        // Input    String str = "peter parker picked a peck of pickled peppers";    String w = "peck";    countOccurrences(str, w);  }}// This code is contributed by gauravrajput1  | 
Python3
| # Python program for the above approachimportre# Function to count total occurrences# of word "w" in String "str"defcountOccurrences(str,w):    # Get the regex to be checked    regexPattern ="\\b"+w +"\\b"        # Variable to count total    # occurrences of the given word    count=0        form inre.finditer(regexPattern, str):        # Increment count        count=count+1            # Print the occurrences of the word    print(count)    # Driver Code# Inputstr="peter parker picked a peck of pickled peppers"w ="peck"countOccurrences(str,w)# This code is contributed by Pushpesh Raj. | 
C#
| // C# program for the above approachusingSystem;usingSystem.Text.RegularExpressions;publicclassGFG {  // Function to count total occurrences  // of word "w" in String "str"  staticvoidcountOccurrences(String str, String w)   {    // Get the regex to be checked    String regexPattern = "\\b"+ w + "\\b";    Regex rx = newRegex(regexPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);    // Variable to count total    // occurrences of the given word    intcount = 0;    while(str.Contains(w)) {      str = str.Replace(w, "");      // Increment count      count++;    }    // Print the occurrences of the word    Console.Write(count + "\n");    return;  }  // Driver Code  publicstaticvoidMain(String[] args)  {    // Input    String str = "peter parker picked a peck of pickled peppers";    String w = "peck";    countOccurrences(str, w);  }}// This code is contributed by gauravrajput1 | 
Javascript
| //// Javascript program for the above approachfunctioncountOccurrences(string, substring) {  varn = 0;  varposition = 0;  while(true) {    position = string.indexOf(substring, position);    if(position != -1) {      n++;      position += substring.length;    } else{      break;    }  }  returnn;}console.log(countOccurrences("peter parker picked a peck of pickled peppers", "peck")); // This code is contributed By Rahul Chauhan | 
1
Time Complexity : O(N)
Auxiliary Space : O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    








