Here's a method I made that should work perfectly right out of the box without throwing any errors,
private static int countMatches(String str, String sub) {
int count = 0;
if(!str.isEmpty() && !sub.isEmpty()) {
for (int i = 0; (i = str.indexOf(sub, i)) != -1; i += sub.length()) {
count++;
}
}
return count;
}
I will now continue to explain what the method does for beginners.
We start at the count 0.
Then we check if both of our strings are NOT empty, knowing they aren't empty we continue with counting for our sub-string, we make a simple loop that counts the sub-string and the loop ends once indexOf
returns -1 which means the sub-string is not found.
Just copy and paste it to your project and run it via executing
int count = countMatches("Hello World", "World");
now count
should return the index of 1 if its being executed.
Happy coding :)
replace
, and then look at how much shorter your string has become to work out how many times it was replaced?