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




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

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.