计算字符串中存在的单词
给定一个单词数组和一个字符串,我们需要计算给定字符串中出现的所有单词。
例子:
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
脚步:
- 从字符串中提取每个单词。
- 对于每个单词,检查它是否在单词数组中(通过创建集合/映射)。如果存在,则增加结果。
下面是上述步骤的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 hs = new HashSet();
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