Occurrences of substring in a string

后端 未结 24 1875
眼角桃花
眼角桃花 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:55

    String str = "helloslkhellodjladfjhello";
    String findStr = "hello";
    int lastIndex = 0;
    int count = 0;
    
    while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
         count++;
         lastIndex += findStr.length() - 1;
    }
    System.out.println(count);
    

    at the end of the loop count is 3; hope it helps

提交回复
热议问题