Count words present in a string

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


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


  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.

Below is the Java implementation of above steps





// 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
        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) {
        return counter;
    public static void main(String[] args) 
        String word[] = { "welcome", "to", "geeks", "portal"};
        String str = "geeksforgeeks is a computer science portal for geeks.";






My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :

Be the First to upvote.
