How to count the number of repetitions of a sequence in a Java string?

I have a line that looks like this:

"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 in a row.

How to do it in Java?

+8
java string
source share
7 answers
 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); 
+10
source share

An countMatches way is Apache StringUtils countMatches

 StringUtils.countMatches("Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!", "is"); 
+27
source share

If you prefer regex, this is a regex solution:

 String example = "Hello my is Joeseph. It is very nice to meet you. isWhat a wonderful day it is!"; Matcher m = Pattern.compile("\\bis\\b").matcher(example); int matches = 0; while(m.find()) matches++; System.out.println(matches); 

In this case, the "is" in "isWhat" is ignored due to the \ b border matching in the pattern

+4
source share
 String haystack = "Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!"; haystack.toLowerCase(); String needle = "is"; int numNeedles = 0; int pos = haystack.indexOf(needle); while(pos >= 0 ){ pos = pos + 1; numNeedles = numNeedles + 1; pos = haystack.indexOf(needle,pos); } System.out.println("the num of " +needle+ "= " +numNeedles); 
+2
source share

split into each "" (empty) and check outgoing line [] with a loop

+1
source share

Here you can find here . It looks weird like Robbie.

+1
source share
 String s = "abcd"; String replace = "."; int count = s.replaceAll("[^" + replace + "]", "").length() / replace.length(); println(count); 
0
source share

All Articles