How to find the count of substring in java

前端 未结 4 1698
走了就别回头了
走了就别回头了 2021-01-01 02:43

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

相关标签:
4条回答
  • 2021-01-01 02:52

    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++;
    
    0 讨论(0)
  • 2021-01-01 02:52

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

    0 讨论(0)
  • 2021-01-01 03:15

    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.

    0 讨论(0)
  • 2021-01-01 03:17

    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 :)

    0 讨论(0)
提交回复
热议问题