How to find substring counter in java

I am trying to find a substring counter in a large string 10,000 characters long. Finally, I need to remove the entire substring. example s = abacacac, substr = ac, num of occurrence = 3and the final line - s = ab. My code is below, it is not efficient for data length of 10,000 characters.

int count =0;
while(s.contains(substr))
{
   s= s.replaceFirst(substr,"");
   count++;    
}
+3
source share
3 answers

What about:

String temp = s.replace(sub, "");
int occ = (s.length() - temp.length()) / sub.length();

Just delete the whole substring, then check the difference on the length of the string before and after the deletion. Split the string temp with the number of characters from the substring, you will get the occurrences.

+8
source

To count a matching substring

System.out.println(s.split(substr, -1).length-1);

To replace a string - you can use the following code

System.out.println(Pattern.compile(s).matcher(substr).replaceAll(""));

0
source

indexOf:

int count = 0;
for (int pos = s.indexOf(substr); pos >= 0; pos = s.indexOf(substr, pos + 1))
    count++;
0

Source: https://habr.com/ru/post/1684497/


All Articles