VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-occurrences-of-a-word-in-string/

⇱ Count occurrences of a word in string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count occurrences of a word in string

Last Updated : 2 May, 2025

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

[Approach 1] Split the String and Count - O(n) Time and O(n) Space

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.


Output
1

[Approach 2] Using Inbuilt Split Function - O(n) Time and O(n) Space

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.


Output
1

[Approach 3] Using Regular Expression - O(n) Time and O(1) Space

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.


Output
1
Comment
Article Tags:
Article Tags: