 GeeksforGeeks App
Open App Browser
Continue

# Count occurrences of a word in string

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 ``#include ` `int` `countOccurrences(``char` `*str, ``char` `*word)``{``    ``char` `*p;` `    ``// split the string by spaces in a``    ``char` `*a;``      ``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;``}`

## C++

 `// C++ program to count the number``// of occurrence of a word in``// the given string``#include ``using` `namespace` `std;` `int` `countOccurrences(``char` `*str,``                    ``string word)``{``    ``char` `*p;` `    ``// split the string by spaces in a``    ``vector 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`

## 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`

## PHP

 ``

## Javascript

 ``

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 ``using` `namespace` `std;` `int` `countOccurrences(string str, string word)``{``    ``// Split the string into words``    ``stringstream ss(str);``    ``string token;``    ``vector 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 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`

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.

## 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`

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.

My Personal Notes arrow_drop_up