统计一个字符串在另外一个字符串出现次数
代码如下:
package me.chunsheng.javatest; import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* Created by wei_spring on //.
* <p>
* 统计一个字符串在另外一个字符串出现的次数
* 正则匹配的方法,前提字符串不是特殊字符串
* eg:finder("adadadadauuada", "ada") 这样会统计不准确的.
* 另外一个遍历的解决了上面那种情况.
* 两者时间如下(纳秒为单位): 正则明显耗时,正则本就不是统计用的!!!
* finder:
* finderTime:
* getCount:
* getCountTime:
*/
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 = ;
int length = source.length() - sub.length();
for (int i = ; i < length; i++) {
String sourceBak = source.substring(i, i + sub.length());
int index = sourceBak.indexOf(sub);
if (index != -) {
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 = ;
while (matcher.find()) {
n++;
}
return n;
}
}