Occurrences of substring in a string

后端 未结 24 2381
眼角桃花
眼角桃花 2020-11-22 03:35

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 = \"helloslkhe         


        
24条回答
  •  面向向阳花
    2020-11-22 03:46

    Here it is, wrapped up in a nice and reusable method:

    public static int count(String text, String find) {
            int index = 0, count = 0, length = find.length();
            while( (index = text.indexOf(find, index)) != -1 ) {                
                    index += length; count++;
            }
            return count;
    }
    

提交回复
热议问题