统计字符串中含指定字符个数

想了一种字符替换的方法,然后比对前后字符串的长度,达到统计指定字符个数的目的。

public class CalcCharTest {

    public static void main(String[] args) {
        String str = "13143948543879847234982123erwefeeeeefwafegegregfweafreg";

		// 方法1
        long startTime = System.currentTimeMillis();
        int num = calcNum1(str, "2");
        System.out.println(num + "-Method 1 :"+ (System.currentTimeMillis() - startTime));

        // 方法2
        long startTime2 = System.currentTimeMillis();
        int stringNum = calcNum2(str, "2");
        System.out.println(stringNum + "-Method 2 :"+ (System.currentTimeMillis() - startTime2));

    }

    /**
     * 统计指定字符个数1
     * @param str
     * @param statStr 统计的字符
     * @return
     */
    public static int calcNum1(String str, String statStr){
        if (str == null || str.indexOf(statStr)==-1) {
            return 0;
        }
        String after = str.replaceAll(statStr, "");
        return str.length() - after.length();
    }

    /**
     * 统计指定字符个数2
     * @param str
     * @param statStr 统计的字符
     * @return
     */
    public static int calcNum2(String str, String statStr) {
        if (str == null || str.indexOf(statStr)==-1) {
            return 0;
        }
        int counter = 0;
        String[] split = str.split("");
        for(String s : split) {
            if (s.equals(statStr)) {
                counter++;
            }
        }
        return counter;
    }

}

方法一实质是正则匹配,源码如下:

public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

// java.util.regex.Matcher#replaceAll
public String replaceAll(String replacement) {
        reset();
        boolean result = find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                appendReplacement(sb, replacement);
                result = find();
            } while (result);
            appendTail(sb);
            return sb.toString();
        }
        return text.toString();
    }

总体来说,第一种方法比第二种循环比对的方法高效点。



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值