我试图找出句子中单词出现的总数。 我尝试了以下代码:
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次。
感谢。
答案 0 :(得分:0)
在匹配后递增lastIndex
时,您的意思是将其增加匹配的长度(indexWord
),而不是输入字符串的长度(findStr
) 。只需替换
lastIndex += findStr.length();
与
lastIndex += indexWord.length();
答案 1 :(得分:0)
试试这段代码
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
答案 2 :(得分:0)
您也可以使用地图。
public static void main(String[] args) {
String value = "This is simple sting with simple have two occurence";
Map<String, Integer> map = new HashMap<>();
for (String w : value.split(" ")) {
if (!w.equals("")) {
Integer n = map.get(w);
n = (n == null) ? 1 : ++n;
map.put(w, n);
}
}
System.out.println("map" + map);
}
答案 3 :(得分:0)
是否有任何理由不使用现成的API解决方案。 这可以通过在apache commons-lang中使用StringUtils来实现,它具有CountMatches方法来计算一个String在另一个String中出现的次数。
E.g。
String input = "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 = "stackoverflow is";
for (String s : Arrays.asList(findStr.split(" "))) {
int occurance = StringUtils.countMatches(input, s);
System.out.println(occurance);
}