Count occurrences of a word in string (original) (raw)
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
Table of Content
- [Approach 1] Split the String and Count - O(n) Time and O(n) Space
- [Approach 2] Using Inbuilt Split Function - O(n) Time and O(n) Space
- [Approach 3] Using Regular Expression - O(n) Time and O(1) Space
[Approach 1] Split the String and Count - O(n) Time and O(n) Space
The idea is to s**plit 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.
C++ `
// C++ program to count occurrences of a word // by splitting the string and counting #include <bits/stdc++.h> using namespace std;
// Function to count occurrences of word in s int countOccurrences(string s, string word) {
int count = 0;
string curr = "";
for (int i = 0; i < s.length(); i++) {
// If current char is space,
// check the built word
if (s[i] == ' ') {
if (curr == word) {
count++;
}
// Reset current word
curr = "";
}
// Else keep building the word
else {
curr += s[i];
}
}
// Check the last word (after loop ends)
if (curr == word) {
count++;
}
return count;}
// Driver code int main() {
string s = "GeeksforGeeks A computer science portal for geeks";
string word = "portal";
// Call function and print result
int res = countOccurrences(s, word);
cout << res << endl;
return 0;}
Java
// Java program to count occurrences of a word // by splitting the string and counting class GfG {
// Function to count occurrences of word in s
static int countOccurrences(String s, String word) {
int count = 0;
String curr = "";
for (int i = 0; i < s.length(); i++) {
// If current char is space,
// check the built word
if (s.charAt(i) == ' ') {
if (curr.equals(word)) {
count++;
}
// Reset current word
curr = "";
}
// Else keep building the word
else {
curr += s.charAt(i);
}
}
// Check the last word (after loop ends)
if (curr.equals(word)) {
count++;
}
return count;
}
// Driver code
public static void main(String[] args) {
String s = "GeeksforGeeks A computer science portal for geeks";
String word = "portal";
// Call function and print result
int res = countOccurrences(s, word);
System.out.println(res);
}}
Python
Python program to count occurrences of a word
by splitting the string and counting
def countOccurrences(s, word):
count = 0
curr = ""
for i in range(len(s)):
# If current char is space,
# check the built word
if s[i] == ' ':
if curr == word:
count += 1
# Reset current word
curr = ""
# Else keep building the word
else:
curr += s[i]
# Check the last word (after loop ends)
if curr == word:
count += 1
return countif name == "main":
s = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
# Call function and print result
res = countOccurrences(s, word)
print(res)C#
// C# program to count occurrences of a word // by splitting the string and counting using System;
class GfG {
// Function to count occurrences of word in s
static int countOccurrences(string s, string word) {
int count = 0;
string curr = "";
for (int i = 0; i < s.Length; i++) {
// If current char is space,
// check the built word
if (s[i] == ' ') {
if (curr == word) {
count++;
}
// Reset current word
curr = "";
}
// Else keep building the word
else {
curr += s[i];
}
}
// Check the last word (after loop ends)
if (curr == word) {
count++;
}
return count;
}
// Driver code
public static void Main() {
string s = "GeeksforGeeks A computer science portal for geeks";
string word = "portal";
// Call function and print result
int res = countOccurrences(s, word);
Console.WriteLine(res);
}}
JavaScript
// JavaScript program to count occurrences of a word // by splitting the string and counting
function countOccurrences(s, word) {
let count = 0;
let curr = "";
for (let i = 0; i < s.length; i++) {
// If current char is space,
// check the built word
if (s[i] === ' ') {
if (curr === word) {
count++;
}
// Reset current word
curr = "";
}
// Else keep building the word
else {
curr += s[i];
}
}
// Check the last word (after loop ends)
if (curr === word) {
count++;
}
return count;}
// Driver code let s = "GeeksforGeeks A computer science portal for geeks"; let word = "portal";
// Call function and print result let res = countOccurrences(s, word); console.log(res);
`
[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.
C++ `
// C++ program to count occurrences of a word // using inbuilt string split #include <bits/stdc++.h> using namespace std;
// Function to count occurrences of word in s int countOccurrences(string s, string word) {
int count = 0;
vector<string> tokens;
// Use stringstream to split the string
stringstream ss(s);
string token;
// Store each word into the vector
while (ss >> token) {
tokens.push_back(token);
}
// Count matching words
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == word) {
count++;
}
}
return count;}
// Driver code int main() {
string s = "GeeksforGeeks A computer science portal for geeks";
string word = "portal";
int res = countOccurrences(s, word);
cout << res << endl;
return 0;}
Java
// Java program to count occurrences of a word // using inbuilt string split class GfG {
// Function to count occurrences of word in s
static int countOccurrences(String s, String word) {
int count = 0;
// Use split function to tokenize string
String[] tokens = s.split(" ");
// Count matching words
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals(word)) {
count++;
}
}
return count;
}
// Driver code
public static void main(String[] args) {
String s = "GeeksforGeeks A computer science portal for geeks";
String word = "portal";
int res = countOccurrences(s, word);
System.out.println(res);
}}
Python
Python program to count occurrences of a word
using inbuilt string split
def countOccurrences(s, word):
count = 0
# Use split function to tokenize string
tokens = s.split(" ")
# Count matching words
for i in range(len(tokens)):
if tokens[i] == word:
count += 1
return countDriver code
if name == "main":
s = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
res = countOccurrences(s, word)
print(res)C#
// C# program to count occurrences of a word // using inbuilt string split using System;
class GfG {
// Function to count occurrences of word in s
static int countOccurrences(string s, string word) {
int count = 0;
// Use Split function to tokenize string
string[] tokens = s.Split(' ');
// Count matching words
for (int i = 0; i < tokens.Length; i++) {
if (tokens[i] == word) {
count++;
}
}
return count;
}
// Driver code
static void Main() {
string s = "GeeksforGeeks A computer science portal for geeks";
string word = "portal";
int res = countOccurrences(s, word);
Console.WriteLine(res);
}}
JavaScript
// JavaScript program to count occurrences of a word // using inbuilt string split
function countOccurrences(s, word) {
let count = 0;
// Use split function to tokenize string
let tokens = s.split(" ");
// Count matching words
for (let i = 0; i < tokens.length; i++) {
if (tokens[i] === word) {
count++;
}
}
return count;}
// Driver code let s = "GeeksforGeeks A computer science portal for geeks"; let word = "portal";
let res = countOccurrences(s, word); console.log(res);
`
[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.
C++ `
// C++ program to count occurrences of a word // using regex #include <bits/stdc++.h> using namespace std;
// Function to count occurrences of word in s int countOccurrences(string s, string word) {
int count = 0;
// Use regex to find words
regex re("\\b\\w+\\b");
auto words_begin = sregex_iterator(s.begin(), s.end(), re);
auto words_end = sregex_iterator();
// Count matching words
for (auto it = words_begin; it != words_end; ++it) {
if (it->str() == word) {
count++;
}
}
return count;}
// Driver code int main() {
string s = "GeeksforGeeks A computer science portal for geeks.";
string word = "portal";
int res = countOccurrences(s, word);
cout << res << endl;
return 0;}
Java
// Java program to count occurrences of a word // using regex import java.util.regex.*;
class GfG {
// Function to count occurrences of word in s
static int countOccurrences(String s, String word) {
int count = 0;
// Use regex matcher
Pattern pattern = Pattern.compile("\\b\\w+\\b");
Matcher matcher = pattern.matcher(s);
// Count matching words
while (matcher.find()) {
if (matcher.group().equals(word)) {
count++;
}
}
return count;
}
// Driver code
public static void main(String[] args) {
String s = "GeeksforGeeks A computer science portal for geeks.";
String word = "portal";
int res = countOccurrences(s, word);
System.out.println(res);
}}
Python
Python program to count occurrences of a word
using regex
import re
def countOccurrences(s, word):
count = 0
# Use finditer to iterate over matches
for match in re.finditer(r'\b\w+\b', s):
if match.group() == word:
count += 1
return countDriver Code
if name == "main":
s = "GeeksforGeeks A computer science portal for geeks."
word = "portal"
res = countOccurrences(s, word)
print(res)C#
// C# program to count occurrences of a word // using regex using System; using System.Text.RegularExpressions;
class GfG {
// Function to count occurrences of word in s
public static int countOccurrences(string s, string word) {
int count = 0;
// Use regex to find matches
MatchCollection matches = Regex.Matches(s, @"\b\w+\b");
// Count matching words
foreach (Match match in matches) {
if (match.Value == word) {
count++;
}
}
return count;
}
// Driver code
public static void Main() {
string s = "GeeksforGeeks A computer science portal for geeks.";
string word = "portal";
int res = countOccurrences(s, word);
Console.WriteLine(res);
}}
JavaScript
// JavaScript program to count occurrences of a word // using regex
function countOccurrences(s, word) {
let count = 0;
// Use matchAll to iterate over words
const regex = /\b\w+\b/g;
const matches = s.matchAll(regex);
for (const match of matches) {
if (match[0] === word) {
count++;
}
}
return count;}
// Driver Code let s = "GeeksforGeeks A computer science portal for geeks."; let word = "portal";
let res = countOccurrences(s, word); console.log(res);
`