我正在尝试查找句子中出现单词的总次数。 我尝试下面的代码:如何获得句子中出现的单词总数
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