String中的Java计数模式

时间:2017-05-15 20:52:34

标签: java

让我们假设你有一个方法,它接受一个模式,也是一个整个字符串......

方法如下:

FrameLayout

所以,输入可能是这样的:

public int count(String pattern, String input) { 
    int count = 0;
    // How to implement the number of occurrences of the pattern?
} 

迭代和查找" ddt"的出现最有效的方式(在复杂性方面)?

3 个答案:

答案 0 :(得分:3)

实现这一目标的一种简单方法是根据给定的split String pattern

int result = input.split(pattern,-1).length - 1;

工作原理:

.split(pattern, -1)  -> split the String into an array according to the pattern given, -1 (negative limit) means the pattern will be applied as many times as possible.
.length  -> take the length of the array
-1 -> the logic requires counting the splitter (i.e. pattern), so if there is only one occurrence, that will split it into two , when subtract 1 -> it gives the count

答案 1 :(得分:1)

你可以做到

public int count(String pattern, String input) { 
    int i = (input.length()-input.replace(pattern, "").length())/pattern.length();
    return i;
}

甚至更短

public int count(String pattern, String input) { 
    return (input.split(pattern, -1).length-1);
}

答案 2 :(得分:1)

您可以使用PatternMatcher类,例如:

public int count(String pattern, String input) { 
    int count = 0;
    Pattern patternObject = Pattern.compile(pattern);
    Matcher matcher = patternObject.matcher(input);
    while(matcher.find()){
        count++;
    }
    return count;
}