count Repeat string - Android java.lang

Android examples for java.lang:String Algorithm

Description

count Repeat string

Demo Code

import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    public static int countRepeat(String src, char c) {
        if (src == null) {
            return 0;
        }//w  w w  . j av  a 2  s  .c  om
        int count = 0;
        for (int i = 0; i < src.length(); i++) {
            Character cr = src.charAt(i);
            if (c == cr) {
                count++;
            }
        }
        return count;
    }
    /**
     * <pre>
     * StringUtil.countRepeat(null, *) = 0
     * StringUtil.countRepeat("", *) = 0
     * StringUtil.countRepeat("abba", null) = 0
     * StringUtil.countRepeat("abba", "") = 0
     * StringUtil.countRepeat("abba", "a") = 2
     * StringUtil.countRepeat("abba", "ab") = 1
     * StringUtil.countRepeat("abba", "xxx") = 0
     * StringUtil.countRepeat("aaaa", "aa") = 3
     * </pre>
     * </p>
     */
    public static int countRepeat(String str, String subStr) {
        if ((str == null) || (str.length() == 0) || (subStr == null)
                || (subStr.length() == 0)) {
            return 0;
        }

        int count = 0;
        int index = 0;

        while ((index = str.indexOf(subStr, index)) != -1) {
            count++;
            index++;
        }

        return count;
    }

}

Related Tutorials