Sample Java Pattern in String

Let's say you have a method that takes a template as well as a whole string ...

The method looks like this:

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

      

So the inputs can be like this:

String input = "sdbwedfddfbcaeeudhsomeothertestddtfdonemoredfdsatdevdb";

String pattern = "ddt";

int result = count(pattern, input);

      

What would be the most efficient way (in terms of complexity) to iterate over and find the occurrence of "ddt"?

+3


source to share


3 answers


An easy way to achieve this is split

the String

according to the given pattern

:

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

      



How it works:

.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

      

+3


source


You could do

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

      



Or even shorter

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

      

+1


source


You can use classes Pattern

and Matcher

for example:

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;
} 

      

+1


source







All Articles