Occurrences of substring in a string

后端 未结 24 1895
眼角桃花
眼角桃花 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 04:05

    The last line was creating a problem. lastIndex would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.

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

提交回复
热议问题