统计一个字符串在另外一个字符串出现次数
代码如下:
package me.chunsheng.javatest; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by wei_spring on 16/10/11. * <p> * 统计一个字符串在另外一个字符串出现的次数 * 正则匹配的方法,前提字符串不是特殊字符串 * eg:finder("adadadadauuada", "ada") 这样会统计不准确的. * 另外一个遍历的解决了上面那种情况. * 两者时间如下(纳秒为单位): 正则明显耗时,正则本就不是统计用的!!! * finder:3 * finderTime:1579549 * getCount:4 * getCountTime:34506 */ public class SubStringCount { public static void main(String[] args) { long current1 = System.nanoTime(); System.out.println("finder:" + finder("adadadadauuada", "ada")); System.out.println("finderTime:" + (System.nanoTime() - current1)); long current2 = System.nanoTime(); System.out.println("getCount:" + getCount("adadadadauuada", "ada")); System.out.println("getCountTime:" + (System.nanoTime() - current2)); } public static int getCount(String source, String sub) { int count = 0; int length = source.length() - sub.length(); for (int i = 0; i < length; i++) { String sourceBak = source.substring(i, i + sub.length()); int index = sourceBak.indexOf(sub); if (index != -1) { count++; } } return count; } public static int finder(String source, String regexStr) { String regex = "[a-zA-Z]+"; if (regexStr != null && !regexStr.equals("")) { regex = regexStr; } Pattern expression = Pattern.compile(regex); Matcher matcher = expression.matcher(source); int n = 0; while (matcher.find()) { n++; } return n; } }
时间: 2024-10-23 13:50:01