Occurrences of substring in a string

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

    I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than str.split(target, -1).length-1

    public static int count(String str, String target) {
        return (str.length() - str.replace(target, "").length()) / target.length();
    }
    

提交回复
热议问题