我正在尝试查找句子中单词出现的总数。 我尝试了以下代码:
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);
}
如果我传递像“stack Solution”这样的字符串,则应该将字符串分成两部分(空格分割),并且需要找到句子中每个字符串出现的次数。如果我只传递一个单词,则计数是完美的。代码甚至必须匹配包含搜索字符串的子字符串。 例如:-句子中“stack”出现了3次,但次数只有2次。
谢谢。
最佳答案
当您在匹配后递增 lastIndex
时,意味着将其递增匹配的长度 (indexWord
),而不是输入单词字符串的长度 (findStr
)。只需更换线路即可
lastIndex += findStr.length();
与
lastIndex += indexWord.length();
关于java - 如何获取一个单词在句子中出现的总次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39585898/