Occurrences of substring in a string

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

    Your lastIndex += findStr.length(); was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always to findStr.length()).

    Here is the fixed version :

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

提交回复
热议问题