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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
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.
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) { 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)); } } |
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.



