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?
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?
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");
StringUtils
meant primarily for use within the framework? Meaning, it works, but Apache’s clearly better in this respect.
Sep 2, 2013 at 19:49
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);
If you prefer regex, here 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, because of the \b boundary matcher in the pattern
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);
char
type able to hold multiple characters?
Sep 5, 2013 at 6:22
split on every " " (blank) and check the outcoming string[] with a loop
This takes into account the length of "replace"
String text = "a.b.c.d";
String replace = ".";
int count = (text.length()- (text.replaceAll(replace, "").length())) / replace.length();
System.out.println(count)