Occurrences of substring in a string

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

    A lot of the given answers fail on one or more of:

    • Patterns of arbitrary length
    • Overlapping matches (such as counting "232" in "23232" or "aa" in "aaa")
    • Regular expression meta-characters

    Here's what I wrote:

    static int countMatches(Pattern pattern, String string)
    {
        Matcher matcher = pattern.matcher(string);
    
        int count = 0;
        int pos = 0;
        while (matcher.find(pos))
        {
            count++;
            pos = matcher.start() + 1;
        }
    
        return count;
    }
    

    Example call:

    Pattern pattern = Pattern.compile("232");
    int count = countMatches(pattern, "23232"); // Returns 2
    

    If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL flag:

    Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
    int count = countMatches(pattern, "1+1+1"); // Returns 2
    

提交回复
热议问题