Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the number of times a sequence occurs in a Java string? [closed]

Tags:

java

string

I have a String that looks like:

"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!". 

I want to count the number of times is is in the string.

How can I do this in Java?

like image 934
Joeseph Avatar asked Mar 07 '11 18:03

Joeseph


2 Answers

An easy way is using Apache StringUtils countMatches

StringUtils.countMatches("Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!", "is");
like image 123
Mikezx6r Avatar answered Sep 20 '22 19:09

Mikezx6r


int index = input.indexOf("is");
int count = 0;
while (index != -1) {
    count++;
    input = input.substring(index + 1);
    index = input.indexOf("is");
}
System.out.println("No of *is* in the input is : " + count);
like image 26
asgs Avatar answered Sep 18 '22 19:09

asgs