回顾最初的问题,我们需要在给定的句子中找到一些给定的关键字,计算出现的次数并知道在哪里。我不太明白“哪里”是什么意思(它是句子中的索引吗?),所以我会通过那个......我还在学习java,一次一步,所以我会看到在适当的时候给那个:-)
必须注意,普通句子(如原始问题中的句子)可以有重复的关键字,因此搜索不能只询问给定关键字“是否存在”,如果存在则将其计为 1。可以有多个相同的。例如:
// Base sentence (added punctuation, to make it more interesting):
String sentence = "Say that 123 of us will come by and meet you, "
+ "say, at the woods of 123woods.";
// Split it (punctuation taken in consideration, as well):
java.util.List<String> strings =
java.util.Arrays.asList(sentence.split(" |,|\\."));
// My keywords:
java.util.ArrayList<String> keywords = new java.util.ArrayList<>();
keywords.add("123woods");
keywords.add("come");
keywords.add("you");
keywords.add("say");
通过查看,“Say”+“come”+“you”+“say”+“123woods”的预期结果将是 5,如果我们使用小写字母,则将“say”计数两次。如果我们不这样做,那么计数应该是 4,“说”被排除在外,“说”被包括在内。美好的。我的建议是:
// Set... ready...?
int counter = 0;
// Go!
for(String s : strings)
{
// Asking if the sentence exists in the keywords, not the other
// around, to find repeated keywords in the sentence.
Boolean found = keywords.contains(s.toLowerCase());
if(found)
{
counter ++;
System.out.println("Found: " + s);
}
}
// Statistics:
if (counter > 0)
{
System.out.println("In sentence: " + sentence + "\n"
+ "Count: " + counter);
}
结果是:
发现:说
发现:来
发现:你
发现:说
发现:123woods
句子:说我们中的 123 个人会来见你,比如说,在 123woods 的树林里。
计数:5