Occurrences of substring in a string

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

    Based on the existing answer(s) I'd like to add a "shorter" version without the if:

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

提交回复
热议问题