![]() |
VOOZH | about |
Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.
Note: The string word should appear in s as a separate word, not as a substring within other words.
Examples:
Input: s = "GeeksforGeeks A computer science portal for geeks", word = "portal"
Output: 1
Explanation: The word "portal" appears once as a separate word in the string.Input: s = "Learning learn learners learned learningly", word = "learn"
Output: 1
Explanation: The word "learn" appears exactly once as a separate word. Words like "learners", "learned", and "learningly" contain "learn" as a substring, but do not count as exact word matches.Input: s = "GeeksforGeeks A computer science portal for geeks", word = "technical"
Output: 0
Table of Content
The idea is to split the string by forming each word character by character while traversing the string. The thought process is that when we encounter a space, it signals the end of a word, so we compare it to the target word. If it matches, we increase the count, and then reset to form the next word. Finally, we also check the last word, since it may not end with a space.
1
The idea is to split the input string into individual words using the space delimiter and then compare each word with the given target word. This approach relies on the observation that using built-in split functions makes it easy to isolate complete words without worrying about manual parsing. We then traverse the resulting array and increment a counter whenever there's a match with the target.
1
The idea is to use regular expressions to directly identify complete words in the string. We define a pattern \b\w+\b that matches only separate words by recognizing word boundaries. Instead of splitting or manually parsing, we iterate through all matches and compare each to the target word, counting the exact matches.
1