Count string a string contains - Android java.lang

Android examples for java.lang:String Algorithm

Description

Count string a string contains

Demo Code

public class Main{
  public static final String EMPTY = ""; //$NON-NLS-1$
  public static final int INDEX_NOT_FOUND = -1;
    /**/*from  www.  jav a2s .  c o  m*/
     * <pre>
     * StringUtil.containCount(&quot;haaaan&quot;, &quot;a&quot;) = 4
     * </pre>
     * 
     */
    public static int containCount(String str, String searchStr) {
        int i = 0;
        int idx = 0;

        if (str == null || searchStr == null) {
            return 0;
        }
        while (true) {
            if ((idx = str.indexOf(searchStr)) > INDEX_NOT_FOUND) {
                str = substring(str, (idx + searchStr.length()),
                        str.length());
                i++;
            } else {
                break;
            }
        }

        return i;
    }
    public static String substring(String str, int beginIndex, int endIndex) {
      if (str == null) {
          return null;
      }

      if (beginIndex < 0 || endIndex < 0) {
          return EMPTY;
      }

      if (endIndex > str.length()) {
          endIndex = str.length();
      }

      if (beginIndex > endIndex || beginIndex > str.length()) {
          return EMPTY;
      }

      return str.substring(beginIndex, endIndex);
  }
    public static String substring(String str, int beginIndex) {
      if (str == null) {
          return null;
      }

      if (beginIndex < 0) {
          return EMPTY;
      }

      if (beginIndex > str.length()) {
          return EMPTY;
      }

      return str.substring(beginIndex);
  }
}

Related Tutorials