我基本上想要搜索字符串的頻率。例如,如果我傳遞了單詞「I」,那麼這個單詞的出現頻率如下:「I去了海灘和I看到三個人」應該是2.我已經構建了這樣的方法在其中我接受一個文本(任意長度),將它分割成一個數組,並通過數組循環遍歷數組,搜索每個索引是否與該單詞匹配。然後,我遞增頻率計數器並將該數字作爲字符串返回。這裏的方法:計算字符串的頻率
private int freq() {
String text = "I went to the beach and I saw three people";
String search = "I";
String[] splitter = text.split("\\s+");
int counter = 0;
for (int i=0; i<splitter.length; i++)
{
if (splitter[i]==search)
{
counter++;
}
else
{
}
}
return counter;
}
}
這是法外:
String final = Integer.toString(freq());
System.out.println(final);
但正如我運行它,我不斷收到0的結果。我不知道我做錯了什麼。
編輯:你們都是正確的!什麼是浪費問題:(的。
爲HashMap的基本代碼,你得到了一個很好的HashMap了吧:)嚴重的,知道基本的數據結構和何時使用它們是巨大的。 –