Count occurrences of a word in string | Set 2 (Using Regular Expressions)
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.
Input: str = “peter parker picked a peck of pickled peppers”, w = “peck”
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”
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”
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”
Below is the implementation of the above approach :
Time Complexity : O(N)
Auxiliary Space : O(N)