How to find the count of substring in java

10,752

Solution 1

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.

Solution 2

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++;

Solution 3

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(""));

Share:
10,752
ajayramesh
Author by

ajayramesh

Updated on June 19, 2022

Comments

  • ajayramesh
    ajayramesh almost 2 years

    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, substr = ac, num of occurrence = 3 and final string is s = ab. My code is below, its not efficient for data of length 10000 characters.

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