回首在原来的问题,我们需要在给定的句子中找到一些给定的关键字,计算出现次数并知道在哪里。我不太明白“where”是什么意思(这是句中的索引吗?),所以我会通过那个...我仍然在学习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");
通过观察它,预期的结果将是5“说” +“来” +“你” +“表示” +“123woods”计数“说”两次,如果我们去小写。如果我们不这样做,那么计数应该是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
你确定逻辑没有缺陷吗?如果您有关键字 - words123和123words,该怎么办?那么在文字中的单词是谁的比赛? – 2011-02-23 12:48:10
无。我只需要确切的单词匹配。 – 2011-02-23 13:18:15