I am trying to find the count of the substring in a big string of length 10000 characters. Finally I need to remove all the substring in it.
example s = abacacac, subs
For countung the substrings I would use indexOf:
int count = 0;
for (int pos = s.indexOf(substr); pos >= 0; pos = s.indexOf(substr, pos + 1))
count++;
To count the matching substring
System.out.println(s.split(substr, -1).length-1);
To get replaced string- you can use following code
System.out.println(Pattern.compile(s).matcher(substr).replaceAll(""));
What about:
String temp = s.replace(sub, "");
int occ = (s.length() - temp.length()) / sub.length();
Just remove all the substring, then check the difference on string length before and after removal. Divide the temp string with number of characters from the substring gives you the occurrences.
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 :)