Occurrences of substring in a string

2018-12-31 05:59发布

Why is the following algorithm not halting for me? (str is the string I am searching in, findStr is the string I am trying to find)

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);

标签: java string
24条回答
牵手、夕阳
2楼-- · 2018-12-31 06:31
public int countOfOccurrences(String str, String subStr) {
  return (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length();
}
查看更多
查无此人
3楼-- · 2018-12-31 06:32

The answer given as correct is no good for counting things like line returns and is far too verbose. Later answers are better but all can be achieved simply with

str.split(findStr).length

It does not drop trailing matches using the example in the question.

查看更多
无与为乐者.
4楼-- · 2018-12-31 06:32

This solution prints the total number of occurrence of a given substring throughout the string, also includes the cases where overlapping matches do exist.

class SubstringMatch{
 public static void main(String []args){
    //String str = "aaaaabaabdcaa";
    //String sub = "aa";
    //String str = "caaab";
    //String sub = "aa";
    String str="abababababaabb";
    String sub = "bab";

    int n = str.length();
    int m = sub.length();

    // index=-1 in case of no match, otherwise >=0(first match position)
    int index=str.indexOf(sub), i=index+1, count=(index>=0)?1:0;
    System.out.println(i+" "+index+" "+count);

    // i will traverse up to only (m-n) position
    while(index!=-1 && i<=(n-m)){   
        index=str.substring(i, n).indexOf(sub);
        count=(index>=0)?count+1:count;
        i=i+index+1;  
        System.out.println(i+" "+index);
    }
    System.out.println("count: "+count);
 }

}

查看更多
宁负流年不负卿
5楼-- · 2018-12-31 06:34
public int indexOf(int ch,
                   int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

So your lastindex value is always 0 and it always finds hello in the string.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 06:34

You can number of occurrences using inbuilt library function:

import org.springframework.util.StringUtils;
StringUtils.countOccurrencesOf(result, "R-")
查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 06:34

Try this one. It replaces all the matches with a -.

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int numberOfMatches = 0;
while (str.contains(findStr)){
    str = str.replaceFirst(findStr, "-");
    numberOfMatches++;
}

And if you don't want to destroy your str you can create a new string with the same content:

String str = "helloslkhellodjladfjhello";
String strDestroy = str;
String findStr = "hello";
int numberOfMatches = 0;
while (strDestroy.contains(findStr)){
    strDestroy = strDestroy.replaceFirst(findStr, "-");
    numberOfMatches++;
}

After executing this block these will be your values:

str = "helloslkhellodjladfjhello"
strDestroy = "-slk-djladfj-"
findStr = "hello"
numberOfMatches = 3
查看更多
登录 后发表回答