Occurrences of substring in a string

后端 未结 24 1871
眼角桃花
眼角桃花 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:53
    public int countOfOccurrences(String str, String subStr) {
      return (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length();
    }
    
    0 讨论(0)
  • 2020-11-22 03:53

    As @Mr_and_Mrs_D suggested:

    String haystack = "hellolovelyworld";
    String needle = "lo";
    return haystack.split(Pattern.quote(needle), -1).length - 1;
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 03:56

    Do you really have to handle the matching yourself ? Especially if all you need is the number of occurences, regular expressions are tidier :

    String str = "helloslkhellodjladfjhello";
    Pattern p = Pattern.compile("hello");
    Matcher m = p.matcher(str);
    int count = 0;
    while (m.find()){
        count +=1;
    }
    System.out.println(count);     
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-11-22 03:58

    You can number of occurrences using inbuilt library function:

    import org.springframework.util.StringUtils;
    StringUtils.countOccurrencesOf(result, "R-")
    
    0 讨论(0)
提交回复
热议问题