Java String Substring Count countSubstringOccurrances(String s1, String SubString)

Here you can find the source of countSubstringOccurrances(String s1, String SubString)

Description

return the number of times the substring occurs in the text - where there are overlaps the count tells how many times the substring could be replaced

License

Apache License

Parameter

Parameter Description
s1 non-null input string to test
SubString non-null Substring to cound

Return

non-negative number of occurrances of the substring

Declaration

public static int countSubstringOccurrances(String s1, String SubString) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  ww w  .j a va 2 s. c o m*/
     * return the number of times the substring occurs in the text -
     * where there are overlaps the count tells how many times the substring could be replaced
     * @param s1 non-null input string to test
     * @param SubString non-null Substring to cound
     * @return non-negative number of occurrances of the substring
     */
    public static int countSubstringOccurrances(String s1, String SubString) {
        int count = 0;
        int index = s1.indexOf(SubString);
        int sublength = SubString.length();
        int start = 0;
        while (index > -1) {
            count++;
            start = index + sublength;
            if (start > s1.length() - sublength)
                return (count);
            index = s1.indexOf(SubString, start);
        }
        return (count);
    }
}

Related

  1. countSubString(final String aString, final String aSubString)
  2. countSubstring(final String text, final String substring)
  3. countSubString(String str, String substr)
  4. countSubstring(String string, String substring)
  5. countSubString(String strToFind, String strSearch)
  6. countSubstrings(String string, String sub)