Count words present in a string
Last Updated :
22 Feb, 2023
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:
- Extract each word from string.
- 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
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class GFG{
static void Main(string[] args)
{
string[] word = { "welcome", "to", "geeks", "portal" };
int n = word.Length;
string str = "geeksforgeeks is a computer science portal for geeks.";
Console.WriteLine(CountOccurrence(word, n, str));
}
static int CountOccurrence(string[] word, int n, string str)
{
int counter = 0;
Regex reg = new Regex(@"[a-zA-Z]+");
MatchCollection matches = reg.Matches(str);
HashSet<string> hs = new HashSet<string>(word);
foreach (Match match in matches)
{
if (hs.Contains(match.Value))
{
counter++;
}
}
return counter;
}
}
}
// This code is contributed by Shivam Tiwari
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 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.
Time Complexity: O(N), N is the size of w.
Auxiliary Space:: O(1).
Similar Reads
Count words in a given string Given a string, count the number of words in it. The words are separated by the following characters: space (' ') or new line ('\n') or tab ('\t') or a combination of these. Recommended PracticeCount number of wordsTry It!Method 1: The idea is to maintain two states: IN and OUT. The state OUT indica
15+ min read
Count of words that are present in all the given sentences Given n sentences. The task is to count the number of words that appear in all of these sentences.Note that every word consists of only lowercase English alphabets. Examples: Input: arr[] = { "there is a cow", "cow is our mother", "cow gives us milk and milk is sweet", "there is a boy who loves cow"
15 min read
Find frequency of each word in a string in Python Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi A
7 min read
Distinct Substring frequency counter Given a string s of length N containing only lowercase English letters and an integer K, the task is to find all distinct substrings of S of length K, and for each substring, count the number of times it occurs in S. You need to return a list of all distinct substrings along with their frequency of
4 min read
Count occurrences of strings formed using words in another string Given a string A and a vector of strings B, the task is to count the number of strings in vector B that only contains the words from A. Examples: Input: A="blue green red yellow"B[]={"blue red", "green pink", "yellow green"}Output: 2 Input: A="apple banana pear"B[]={"apple", "banana apple", "pear ba
7 min read