Open In App

Count occurrences of a word in string

Last Updated : 04 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to count the number
// of occurrence of a word in
// the given string
#include <bits/stdc++.h>
using namespace std;
 
int countOccurrences(char *str,
                    string word)
{
    char *p;
 
    // split the string by spaces in a
    vector<string> a;
 
    p = strtok(str, " ");
    while (p != NULL)
    {
        a.push_back(p);
        p = strtok(NULL, " ");
    }
 
    // search for pattern in a
    int c = 0;
    for (int i = 0; i < a.size(); i++)
 
        // if match found increase count
        if (word == a[i])
            c++;
    return c;
}
 
// Driver code
int main()
{
    char str[] = "GeeksforGeeks A computer science portal for geeks ";
    string word = "portal";
    cout << countOccurrences(str, word);
    return 0;
}
 
// This code is contributed by
// sanjeev2552


C




// C program to count the number
// of occurrence of a word in
// the given string
#include <stdio.h>
#include <string.h>
 
int countOccurrences(char *str, char *word)
{
    char *p;
 
    // split the string by spaces in a
    char *a[300];
      int index=0;
 
    p = strtok(str, " ");
    while (p != NULL)
    {
        a[index++]=(p);
        p = strtok(NULL, " ");
    }
 
    // search for pattern in a
    int c = 0;
    for (int i = 0; i < index; i++)
        // if match found increase count
        if (strcmp(word , a[i])==0){
            c++;
        }
    return c;
}
 
// Driver code
int main()
{
    char str[] = "GeeksforGeeks A computer science portal for geeks ";
    char word[] = "portal";
    printf("%d",countOccurrences(str, word));
    return 0;
}


Java




// Java program to count the number
// of occurrence of a word in
// the given string
import java.io.*;
 
class GFG {
 
static int countOccurrences(String str, String word)
{
    // split the string by spaces in a
    String a[] = str.split(" ");
 
    // search for pattern in a
    int count = 0;
    for (int i = 0; i < a.length; i++)
    {
    // if match found increase count
    if (word.equals(a[i]))
        count++;
    }
 
    return count;
}
 
// Driver code
public static void main(String args[])
{
    String str = "GeeksforGeeks A computer science portal for geeks ";
    String word = "portal";
    System.out.println(countOccurrences(str, word));
}
}
 
/*This code is contributed by Nikita Tiwari.*/


Python 3




# Python program to count the number of occurrence
# of a word in the given string
 
def countOccurrences(str, word):
     
    # split the string by spaces in a
    a = str.split(" ")
 
    # search for pattern in a
    count = 0
    for i in range(0, len(a)):
         
        # if match found increase count
        if (word == a[i]):
           count = count + 1
            
    return count      
 
# Driver code
str ="GeeksforGeeks A computer science portal for geeks  "
word ="portal"
print(countOccurrences(str, word))


C#




// C# program to count the number
// of occurrence of a word in
// the given string
using System;
 
class GFG
{
static int countOccurrences(string str,
                           string word)
{
    // split the string by spaces
    string[] a = str.Split(' ');
 
    // search for pattern in string
    int count = 0;
    for (int i = 0; i < a.Length; i++)
    {
         
    // if match found increase count
    if (word.Equals(a[i]))
        count++;
    }
 
    return count;
}
 
// Driver code
public static void Main()
{
    string str = "GeeksforGeeks A computer science portal for geeks ";
    string word = "portal";
    Console.Write(countOccurrences(str, word));
}
}
 
// This code is contributed
// by ChitraNayal


Javascript




<script>
 
// Javascript program to count the number
// of occurrence of a word in
// the given string
     
    function countOccurrences(str,word)
    {
        // split the string by spaces in a
    let a = str.split(" ");
  
    // search for pattern in a
    let count = 0;
    for (let i = 0; i < a.length; i++)
    {
    // if match found increase count
    if (word==(a[i]))
        count++;
    }
  
    return count;
    }
    // Driver code
    let str = "GeeksforGeeks A computer
    science portal for geeks ";
    let word = "portal";
    document.write(countOccurrences(str, word));
     
     
    // This code is contributed by avanitrachhadiya2155
     
</script>


PHP




<?php
// PHP program to count the number
// of occurrence of a word in
// the given string
 
function countOccurrences($str, $word)
{
    // split the string by spaces
    $a = explode(" ", $str);
 
    // search for pattern in string
    $count = 0;
    for ($i = 0; $i < sizeof($a); $i++)
    {
         
    // if match found increase count
    if ($word == $a[$i])
        $count++;
    }
 
    return $count;
}
 
// Driver code
$str = "GeeksforGeeks A computer science portal for geeks ";
$word = "portal";
echo (countOccurrences($str, $word));
 
// This code is contributed
// by ChitraNayal
?>


Output

1











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++




// C++ program to count the number of occurrence
// of a word in the given string
#include <bits/stdc++.h>
using namespace std;
 
int countOccurrences(string str, string word)
{
    // Split the string into words
    stringstream ss(str);
    string token;
    vector<string> wordslist;
 
    while (ss >> token) {
        wordslist.push_back(token);
    }
 
    // Count the number of occurrences of the given word
    int count = 0;
    for (int i = 0; i < wordslist.size(); i++) {
        if (wordslist[i] == word) {
            count++;
        }
    }
 
    return count;
}
 
// Driver code
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
{
 
  // Function to count the number of occurrences of a word
  // in the given string
  static int countOccurrences(String str, String word)
  {
 
    // Splitting the string into words
    List<String> wordslist
      = Arrays.asList(str.split("\\s+"));
 
    // Counting the frequency of the given word
    return Collections.frequency(wordslist, word);
  }
 
  public static void main(String[] args)
  {
    // Input string
    String str
      = "GeeksforGeeks A computer science portal for geeks  ";
 
    // Word to be counted
    String word = "portal";
 
    // Printing the count of occurrences of the given
    // word in the input string
    System.out.println(countOccurrences(str, word));
  }
}


Python3




# Python program to count the number of occurrence
# of a word in the given string
def countOccurrences(str, word):
 
    wordslist = list(str.split())
    return wordslist.count(word)
 
 
# Driver code
str = "GeeksforGeeks A computer science portal for geeks  "
word = "portal"
print(countOccurrences(str, word))
 
# This code is contributed by vikkycirus


C#




using System;
using System.Collections.Generic;
 
public class GFG{
    // Function to count the number of occurrences of a word
    // in the given string
    static int CountOccurrences(string str, string word){
        // Splitting the string into words
        List<string> wordsList = new List<string>(str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
 
        // Counting the frequency of the given word
        return wordsList.FindAll(w => w == word).Count;
    }
 
    public static void Main(string[] args){
        // Input string
        string str = "GeeksforGeeks A computer science portal for geeks  ";
 
        // Word to be counted
        string word = "portal";
 
        // Printing the count of occurrences of the given
        // word in the input string
        Console.WriteLine(CountOccurrences(str, word));
    }
}


Javascript




// Javascript program to count the number of occurrence
// of a word in the given string
function countOccurrences(str, word) {
  // Split the string into words
  let wordslist = str.split(" ");
 
  // Count the number of occurrences of the given word
  let count = 0;
  for (let i = 0; i < wordslist.length; i++) {
    if (wordslist[i] === word) {
      count++;
    }
  }
 
  return count;
}
 
// Driver code to test above functions
let str = "GeeksforGeeks A computer science portal for geeks";
let word = "portal";
console.log(countOccurrences(str, word));
// THIS CODE IS CONTRIBUTED BY KANCHAN AGARWAL


Output

1











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) {
    // Use regular expression to find all occurrences of the word in the string
    regex regex_word(word);
    sregex_iterator it(str.begin(), str.end(), regex_word);
    sregex_iterator end;
 
    // Calculate the count of occurrences
    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) {
        // Use regular expression to find all occurrences of the word in the string
        Pattern pattern = Pattern.compile("\\b" + Pattern.quote(word) + "\\b");
        Matcher matcher = pattern.matcher(str);
 
        // Calculate the count of occurrences
        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))
 
# Example usage:
string = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
count = count_word_occurrences2(string, word)
print(f"Occurrences of Word = {count} Time"# Output: Occurrences of Word = 1 Time


C#




using System;
using System.Text.RegularExpressions;
 
class Program
{
    static int CountWordOccurrences(string input, string word)
    {
        // Use regular expression to find all occurrences of the word in the input string
        Regex regex = new Regex(word);
        MatchCollection matches = regex.Matches(input);
 
        // Calculate the count of occurrences
        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 to count occurrences of a word in a string
function count_word_occurrences2(string, word) {
    // Use regular expression to find all occurrences of the word in the string
    const regex = new RegExp(word, 'g');
    const matches = string.match(regex);
 
    // Return the count of occurrences
    return matches ? matches.length : 0;
}
 
// Example usage:
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


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.



Similar Reads

Count occurrences of a word in string | Set 2 (Using Regular Expressions)
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: 1Explanation: There is only one occurrence of the word "peck" in the given string. Therefore, the output is 1. Inpu
4 min read
Python - Count occurrences of each word in given text file
Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the word is already present in the dictionary we increm
4 min read
Remove all occurrences of a word from a given string using Z-algorithm
Given two strings str of length N and word of length M, the task is to remove all the occurrences of the string word from the string str. Examples: Input: str = "asmGeeksasmasmForasmGeeks", word = "asm" Output: GeeksForGeeks Explanation: Removing "asm" from the string, str modifies str to GeeksForGeeks Input: str = "Z-kmalgorithmkmiskmkmkmhelpfulkm
15+ min read
Remove all continuous occurrences of 'a' and all occurrences of 'b'
Given a string str, the task is to remove all the continuous occurrences of a and all occurrences of b and print the resultant string. Examples Input: str = "abcddabcddddabbbaaaaaa" Output: acddacdddda 'abcddabcddddabbbaaaaaa' will not result in 'acddacddddaa' because after removing the required occurrences, the string will become 'acddacddddaa' wh
10 min read
Find all occurrences of a given word in a matrix
Given a 2D grid of characters and a word, find all occurrences of given word in grid. A word can be matched in all 8 directions at any point. Word is said be found in a direction if all characters match in this direction (not in zig-zag form). The solution should print all coordinates if a cycle is found. i.e. The 8 directions are, Horizontally Lef
12 min read
Count occurrences of a string that can be constructed from another given string
Given two strings str1 and str2 where str1 being the parent string. The task is to find out the number of string as str2 that can be constructed using letters of str1. Note: All the letters are in lowercase and each character should be used only once. Examples: Input: str1 = "geeksforgeeks", str2 = "geeks" Output: 2 Input: str1 = "geekgoinggeeky",
5 min read
Word Ladder (Length of shortest chain to reach a target word)
Given a dictionary, and two words 'start' and 'target' (both of same length). Find length of the smallest chain from 'start' to 'target' if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the 'target' word exists in dic
15+ min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
C program to find and replace a word in a File by another given word
Pre-requisite: File Handling in CGiven a file containing some text, and two strings wordToBeFind and wordToBeReplacedWith, the task is to find all occurrences of the given word 'wordToBeFind' in the file and replace them with the given word ‘wordToBeReplacedWith’. Examples: Input : File = "xxforxx xx for xx", wordToBeFind = "xx", wordToBeReplacedWi
3 min read
Find the word from a given sentence having given word as prefix
Given a string S representing a sentence and another string word, the task is to find the word from S which has the string word as a prefix. If no such word is present in the string, print -1. Examples: Input: S = "Welcome to Geeksforgeeks", word="Gee"Output: GeeksforgeeksExplanation:The word "Geeksforgeeks" in the sentence has the prefix "Gee". In
8 min read
Practice Tags :