回首在原來的問題,我們需要在給定的句子中找到一些給定的關鍵字,計算出現次數並知道在哪裏。我不太明白「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