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.

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.

Below is the Java implementation of above steps

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
          
    }
  
}

chevron_right


Output:

2

This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.