文中の単語の出現回数を調べようとしています。 私は、次のコードを試してみました:文中の単語の出現回数を取得するには
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つ(スペース分割)に分割し、文の中で、各文字列の発生のないを見つける必要があるべきではありません。私は1つの単語を渡す場合、カウントは完璧です。コードは、検索された文字列を含む部分文字列にも一致する必要があります。 例: - 文章で「スタック」のApperが3回カウントされますが、カウントは2だけです。
ありがとうございました。
'lastIndex + = findStr.length();を' lastIndex + = indexWord.length(); 'に置き換えますか? – qxz
great.itsはうまくいきました。時間を節約してくれてありがとう。 –
回答を追加して、この質問に解決済みとマークすることができます – qxz