我正在嘗試查找句子中出現單詞的總次數。 我嘗試下面的代碼:如何獲得句子中出現的單詞總數
String str = "This is stackoverflow and you will find great solutions here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";
String findStr = "hello World";
String[] split=findStr.split(" ");
for(int i=0;i<split.length;i++){
System.out.println(split[i]);
String indexWord=split[i];
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(indexWord,lastIndex);
System.out.println(lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println("Count for word "+indexWord+" is : "+count);
}
如果我傳遞的字符串,如「棧解決方案」,該字符串應該被分成兩個(空間分割),並需要找到沒有每個字符串的出現在句中。如果我只傳遞一個單詞,則計數是完美的。代碼必須匹配包含搜索字符串的子字符串。 例如: - 在句子「堆棧」中出現三次,但計數僅爲2.
謝謝。
用'lastIndex + = indexWord.length();'替換'lastIndex + = findStr.length();' – qxz
great.its現在工作正常。感謝您節省我的時間。 –
我將添加一個答案,以便將此問題標記爲已解決 – qxz