![]() |
VOOZH | about |
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
regex = "\\bw\\b"
Below is the implementation of the above approach :
1
Time Complexity : O(N)
Auxiliary Space : O(N)