给定一个单词数组和一个字符串,我们需要计算给定字符串中存在的所有单词。
null
例如:
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
步骤:
- 从字符串中提取每个单词。
- 对于每个单词,检查它是否在单词数组中(通过创建set/map)。如果存在,则增加结果。
下面是上述步骤的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)); } } |
输出:
2
本文由 里沙布·贾因 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END