【发布时间】:2016-09-20 04:49:53
【问题描述】:
我试图找出一个句子中单词出现的总数。 我尝试了以下代码:
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);
}
如果我传递“堆栈解决方案”之类的字符串,则该字符串应拆分为两个(空格拆分),并且需要找到句子中每个字符串的出现次数。如果我只传递一个单词,则计数是完美的.代码必须匹配包含搜索字符串的子字符串。 eg:-句子中“stack”出现了3次,但计数只有2次。
谢谢。
【问题讨论】:
-
用
lastIndex += indexWord.length();替换lastIndex += findStr.length();? -
太棒了。它现在工作正常。感谢您节省我的时间。
-
我将添加一个答案,以便将此问题标记为已解决
标签: java