Count occurrences of a word in string
Last Updated :
04 Nov, 2023
You are given a string and a word your task is that count the number of occurrences of the given word in the string and print the number of occurrences of the word.
Examples:
Input : string = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
Output : Occurrences of Word = 1 Time
Input : string = "GeeksforGeeks A computer science portal for geeks"
word = "technical"
Output : Occurrences of Word = 0 Time
Approach:
- First, we split the string by spaces in a
- Then, take a variable count = 0 and in every true condition we increment the count by 1
- Now run a loop at 0 to length of string and check if our string is equal to the word
- if condition is true then we increment the value of count by 1 and in the end, we print the value of count.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int countOccurrences( char *str,
string word)
{
char *p;
vector<string> a;
p = strtok (str, " " );
while (p != NULL)
{
a.push_back(p);
p = strtok (NULL, " " );
}
int c = 0;
for ( int i = 0; i < a.size(); i++)
if (word == a[i])
c++;
return c;
}
int main()
{
char str[] = "GeeksforGeeks A computer science portal for geeks " ;
string word = "portal" ;
cout << countOccurrences(str, word);
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int countOccurrences( char *str, char *word)
{
char *p;
char *a[300];
int index=0;
p = strtok (str, " " );
while (p != NULL)
{
a[index++]=(p);
p = strtok (NULL, " " );
}
int c = 0;
for ( int i = 0; i < index; i++)
if ( strcmp (word , a[i])==0){
c++;
}
return c;
}
int main()
{
char str[] = "GeeksforGeeks A computer science portal for geeks " ;
char word[] = "portal" ;
printf ( "%d" ,countOccurrences(str, word));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int countOccurrences(String str, String word)
{
String a[] = str.split( " " );
int count = 0 ;
for ( int i = 0 ; i < a.length; i++)
{
if (word.equals(a[i]))
count++;
}
return count;
}
public static void main(String args[])
{
String str = "GeeksforGeeks A computer science portal for geeks " ;
String word = "portal" ;
System.out.println(countOccurrences(str, word));
}
}
|
Python 3
def countOccurrences( str , word):
a = str .split( " " )
count = 0
for i in range ( 0 , len (a)):
if (word = = a[i]):
count = count + 1
return count
str = "GeeksforGeeks A computer science portal for geeks "
word = "portal"
print (countOccurrences( str , word))
|
C#
using System;
class GFG
{
static int countOccurrences( string str,
string word)
{
string [] a = str.Split( ' ' );
int count = 0;
for ( int i = 0; i < a.Length; i++)
{
if (word.Equals(a[i]))
count++;
}
return count;
}
public static void Main()
{
string str = "GeeksforGeeks A computer science portal for geeks " ;
string word = "portal" ;
Console.Write(countOccurrences(str, word));
}
}
|
Javascript
<script>
function countOccurrences(str,word)
{
let a = str.split( " " );
let count = 0;
for (let i = 0; i < a.length; i++)
{
if (word==(a[i]))
count++;
}
return count;
}
let str = "GeeksforGeeks A computer
science portal for geeks " ;
let word = "portal" ;
document.write(countOccurrences(str, word));
</script>
|
PHP
<?php
function countOccurrences( $str , $word )
{
$a = explode ( " " , $str );
$count = 0;
for ( $i = 0; $i < sizeof( $a ); $i ++)
{
if ( $word == $a [ $i ])
$count ++;
}
return $count ;
}
$str = "GeeksforGeeks A computer science portal for geeks " ;
$word = "portal" ;
echo (countOccurrences( $str , $word ));
?>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using Count() function in python:
- First, we split the string by spaces and store in list.
- We use count() to find count of that word in list.
Below is the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int countOccurrences(string str, string word)
{
stringstream ss(str);
string token;
vector<string> wordslist;
while (ss >> token) {
wordslist.push_back(token);
}
int count = 0;
for ( int i = 0; i < wordslist.size(); i++) {
if (wordslist[i] == word) {
count++;
}
}
return count;
}
int main()
{
string str = "GeeksforGeeks A computer science portal "
"for geeks" ;
string word = "portal" ;
cout << countOccurrences(str, word);
return 0;
}
|
Java
import java.util.*;
public class Main
{
static int countOccurrences(String str, String word)
{
List<String> wordslist
= Arrays.asList(str.split( "\\s+" ));
return Collections.frequency(wordslist, word);
}
public static void main(String[] args)
{
String str
= "GeeksforGeeks A computer science portal for geeks " ;
String word = "portal" ;
System.out.println(countOccurrences(str, word));
}
}
|
Python3
def countOccurrences( str , word):
wordslist = list ( str .split())
return wordslist.count(word)
str = "GeeksforGeeks A computer science portal for geeks "
word = "portal"
print (countOccurrences( str , word))
|
C#
using System;
using System.Collections.Generic;
public class GFG{
static int CountOccurrences( string str, string word){
List< string > wordsList = new List< string >(str.Split( new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
return wordsList.FindAll(w => w == word).Count;
}
public static void Main( string [] args){
string str = "GeeksforGeeks A computer science portal for geeks " ;
string word = "portal" ;
Console.WriteLine(CountOccurrences(str, word));
}
}
|
Javascript
function countOccurrences(str, word) {
let wordslist = str.split( " " );
let count = 0;
for (let i = 0; i < wordslist.length; i++) {
if (wordslist[i] === word) {
count++;
}
}
return count;
}
let str = "GeeksforGeeks A computer science portal for geeks" ;
let word = "portal" ;
console.log(countOccurrences(str, word));
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Reference: split function python
METHOD 3:Using re.findall module in python.
APPROACH:
The above code uses the re module to find all non-overlapping occurrences of the given word in the given string, and returns the count of those occurrences.
ALGORITHM:
1.Use the re.findall() method to find all non-overlapping occurrences of the given word in the given string.
2.Return the length of the resulting list of occurrences.
C++
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int count_word_occurrences2( const string& str, const string& word) {
regex regex_word(word);
sregex_iterator it(str.begin(), str.end(), regex_word);
sregex_iterator end;
int count = 0;
while (it != end) {
count++;
++it;
}
return count;
}
int main() {
string str = "GeeksforGeeks A computer science portal for geeks" ;
string word = "portal" ;
int count = count_word_occurrences2(str, word);
cout << "Occurrences of Word = " << count << " Time" << endl;
return 0;
}
|
Java
import java.util.regex.*;
public class WordOccurrences {
public static int countWordOccurrences(String str, String word) {
Pattern pattern = Pattern.compile( "\\b" + Pattern.quote(word) + "\\b" );
Matcher matcher = pattern.matcher(str);
int count = 0 ;
while (matcher.find()) {
count++;
}
return count;
}
public static void main(String[] args) {
String str = "GeeksforGeeks A computer science portal for geeks" ;
String word = "portal" ;
int count = countWordOccurrences(str, word);
System.out.println( "Occurrences of Word = " + count + " Time" );
}
}
|
Python3
import re
def count_word_occurrences2(string, word):
return len (re.findall(word, string))
string = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
count = count_word_occurrences2(string, word)
print (f "Occurrences of Word = {count} Time" )
|
C#
using System;
using System.Text.RegularExpressions;
class Program
{
static int CountWordOccurrences( string input, string word)
{
Regex regex = new Regex(word);
MatchCollection matches = regex.Matches(input);
int count = matches.Count;
return count;
}
static void Main( string [] args)
{
string input = "GeeksforGeeks A computer science portal for geeks" ;
string word = "portal" ;
int count = CountWordOccurrences(input, word);
Console.WriteLine( "Occurrences of Word = " + count + " Time" );
}
}
|
Javascript
function count_word_occurrences2(string, word) {
const regex = new RegExp(word, 'g' );
const matches = string.match(regex);
return matches ? matches.length : 0;
}
const string = "GeeksforGeeks A computer science portal for geeks" ;
const word = "portal" ;
const count = count_word_occurrences2(string, word);
console.log(`Occurrences of Word = ${count} Time`);
|
Output
Occurrences of Word = 1 Time
Time complexity: O(n),where n is the length of the string.
Space complexity: O(m), where m is the number of occurrences of the word in the string.
Please Login to comment...