Skip to content
Related Articles
Open in App
Not now

Related Articles

Count words present in a string

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 21 Jan, 2023
Improve Article
Save Article

Given an array of words and a string, we need to count all words that are present in given string. 

Examples:

Input : words[] = { "welcome", "to", "geeks", "portal"}
            str = "geeksforgeeks is a computer science portal for geeks."
Output :  2
Two words "portal" and "geeks" is present in str.


Input : words[] = {"Save", "Water", "Save", "Yourself"}
        str     = "Save"
Output :1

Steps:

  1. Extract each word from string.
  2. For each word, check if it is in word array(by creating set/map). If present, increment result.

Implementation:

C++




#include<bits/stdc++.h>
using namespace std;
 
 
 
// function to count occurrence
int countOccurrence(string word[], int n, string str)
{
    // counter
    int counter = 0;
 
    // for extracting words
    regex reg("[a-zA-Z]+");
    sregex_iterator it(str.begin(), str.end(), reg);
 
    // HashSet for quick check whether
    // a word in str present in word[] or not
    unordered_set<string> hs;
    for (int i=0; i<n; i++)
        hs.insert(word[i]);
 
    while (it != sregex_iterator())
    {
        if (hs.find(it->str()) != hs.end())
            ++counter;
        it++;
    }
 
    return counter;
}
 
int main()
{
    string word[] = { "welcome", "to", "geeks", "portal" };
    int n = sizeof(word)/sizeof(word[0]);
 
    string str = "geeksforgeeks is a computer science portal for geeks.";
 
    cout << countOccurrence(word, n, str);
    return 0;
}
// This code contributed by Ajax

Java




// Java program to count number
// of words present in a string
 
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Test {
    static int countOccurrence(String[] word, String str)
    {
        // counter
        int counter = 0;
 
        // for extracting words
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(str);
 
        // HashSet for quick check whether
        // a word in str present in word[] or not
        HashSet<String> hs = new HashSet<String>();
 
        for (String string : word) {
            hs.add(string);
        }
 
        while (m.find()) {
            if (hs.contains(m.group()))
                counter++;
        }
 
        return counter;
    }
 
    public static void main(String[] args)
    {
        String word[]
            = { "welcome", "to", "geeks", "portal" };
 
        String str
            = "geeksforgeeks is a computer science portal for geeks.";
 
        System.out.println(countOccurrence(word, str));
    }
}

Python3




import re
 
# function to count occurrence
def countOccurrence(word, n, str):
    # counter
    counter = 0
 
    # for extracting words
    reg = re.compile("[a-zA-Z]+")
    it = re.finditer(reg, str)
 
    # HashSet for quick check whether
    # a word in str present in word[] or not
    hs = set(word)
 
    for match in it:
        if match.group() in hs:
            counter += 1
 
    return counter
 
word = ["welcome", "to", "geeks", "portal"]
n = len(word)
 
str = "geeksforgeeks is a computer science portal for geeks."
 
print(countOccurrence(word, n, str))

Javascript




// function to count occurrence of words in a string
function countOccurrence(word, n, str) {
    // counter
    let counter = 0;
 
    // for extracting words
    let reg = new RegExp("[a-zA-Z]+", "g");
    let match;
 
    // HashMap for quick check whether
    // a word in str present in word[] or not
    let hm = new Map();
    for (let i = 0; i < n; i++) {
        hm.set(word[i], true);
    }
 
    while ((match = reg.exec(str)) !== null) {
        if (hm.has(match[0])) {
            counter++;
        }
    }
    return counter;
}
 
let word = [ "welcome", "to", "geeks", "portal" ];
let n = word.length;
let str = "geeksforgeeks is a computer science portal for geeks.";
console.log(countOccurrence(word, n, str));
// This code is contributed by Shivam Tiwari

Output

2

Time Complexity: O(N), N is the length of the word.
Auxiliary Space: O(1).

Method:  First iterate the words using for loop and Check if that word is present in the given string or not if present then increments the count value. Finally, print the count value.

Implementation:

C++




// C++ program to count number
// of words present in a string
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
  vector<string> w({ "welcome", "to", "geeks", "portal" });
  string s = "geeksforgeeks is a computer science portal for geeks.";
 
  int c = 0;
 
  // iterating words
  for(int i=0; i<w.size(); i++)
  {
 
    // checking if word is present in the string or
    // not
    if(s.find(w[i]) != string::npos)
    {
 
      // if present then it increments the count
      // value
      c = c+1;
    }
  }
 
  // printing the result
  cout<< c <<endl;
  return 0;
}
 
// This code is contributed by Srj_27

Java




// A Java program to to implement above approach
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
        String[] w = { "welcome", "to", "geeks", "portal" };
        String s
            = "geeksforgeeks is a computer science portal for geeks.";
        int c = 0;
        // iterating words
        for (int i = 0; i < w.length; i++) {
            // checking if word is present in the string or
            // not
            if (s.contains(w[i])) {
                // if present then it increments the count
                // value
                c = c + 1;
            }
        }
        // printing the result
        System.out.println(c);
    }
}
 
// This code is contributed by Karandeep1234

Python3




# python code to count words present in a string
w=["welcome", "to", "geeks", "portal"]
s="geeksforgeeks is a computer science portal for geeks."
c=0
#iterating words
for i in w:
  #checking if word is present in the string or not
  if i in s:
    # if present then it increments the count value
    c+=1
# printing the result
print(c)
 
 
# this code is contributed by gangarajula laxmi

C#




using System;
 
public class GFG {
 
    static public void Main()
    {
        string[] w = { "welcome", "to", "geeks", "portal" };
        string s
            = "geeksforgeeks is a computer science portal for geeks.";
        int c = 0;
        // iterating words
        for (int i = 0; i < w.Length; i++) {
            // checking if word is present in the string or
            // not
            if (s.Contains(w[i])) {
                // if present then it increments the count
                // value
                c = c + 1;
            }
        }
        // printing the result
        Console.WriteLine(c);
    }
}
// This code is contributed by Potta Lokesh

Javascript




// Javascript program to count number
// of words present in a string
 
  let w= ["welcome", "to", "geeks", "portal"];
  let s = "geeksforgeeks is a computer science portal for geeks.";
 
  let c = 0;
 
  // iterating words
  for(let i = 0; i < w.length; i++)
  {
 
    // checking if word is present in the string or
    // not
    if(s.indexOf(w[i]) != -1)
    {
 
      // if present then it increments the count
      // value
      c = c+1;
    }
  }
 
  // printing the result
  console.log(c)
 
// This code is contributed by poojaagarwal2.

Output

2

Time Complexity: O(N), N is the size of w.
Auxiliary Space:: O(1).

This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!