想了一种字符替换的方法,然后比对前后字符串的长度,达到统计指定字符个数的目的。
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();
}
总体来说,第一种方法比第二种循环比对的方法高效点。