I have to String objects:
String first = \"/Some object that has a loop in it object/\";
String second = \"object\";
What I need to do is find
You can either split the String
on the second String
and count the length of the resulting array, it will have one more element that that number of occurrences. Or you can use Pattern
and Matcher
, which is a slightly more proper approach.
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
String first = "/Some object that has a loop in it object/";
String second = "object";
System.out.println(first.split(Pattern.quote(second)).length - 1);
final Pattern pattern = Pattern.compile(Pattern.quote(second));
final Matcher matcher = pattern.matcher(first);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
Don't forget to use Pattern.quote
just in case.