Count occurrences of a word in string - GeeksforGeeks

06 Oct, 2021
You are given a string and a word your task is that count the number of the occurrence 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++
Java
Python 3
C#
PHP
Javascript
// 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 codeint 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 program to count the number// of occurrence of a word in// the given stringimport 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 codepublic 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 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 codestr ="GeeksforGeeks A computer science portal for geeks  "word ="portal"print(countOccurrences(str, word))
// C# program to count the number// of occurrence of a word in// the given stringusing 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 codepublic 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// 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?>
<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>
Output: 
1
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:
Python3
# Python program to count the number of occurrence# of a word in the given stringdef countOccurrences(str, word):     wordslist = list(str.split())    return wordslist.count(word)  # Driver codestr = "GeeksforGeeks A computer science portal for geeks  "word = "portal"print(countOccurrences(str, word)) # This code is contributed by vikkycirus
1
YouTubeGeeksforGeeks502K subscribersCount occurences of a word in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=AFj5gEmjimE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Reference : split function python 
ukasp
sanjeev2552
vikkycirus
avanitrachhadiya2155
saurabh1990aror
CoderSaty
Python
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types