Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java count pattern in String [duplicate]

Tags:

java

Lets say you have a method which takes in a pattern and also an entire 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 could be 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 and find the occurrences of "ddt"?

like image 607
PacificNW_Lover Avatar asked Sep 19 '26 21:09

PacificNW_Lover


2 Answers

A simple way to achieve that is to 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
like image 117
Yahya Avatar answered Sep 22 '26 11:09

Yahya


You can use Pattern and Matcher classes, e.g.:

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;
} 
like image 26
Darshan Mehta Avatar answered Sep 22 '26 11:09

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!