1. 程式人生 > >計算字串中含有的某個字元的個數

計算字串中含有的某個字元的個數

有如下方法:

String testString = "a,b,c,d"
1)using apache commons
int apache = StringUtils.countMatches(testString, ".");
System.out.println("apache = " + apache);
2) Using Spring Framework's
int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
3) Using replace
int replace = testString.length
() - testString.replace(".", "").length(); System.out.println("replace = " + replace);
4) Using replaceAll (case 1)
int replaceAll = testString.replaceAll("[^.]", "").length();
5) Using replaceAll (case 2)
int replaceAllCase2 = testString.length() - testString.replaceAll("\\.", "").length();
System.out
.println("replaceAll (second case) = " + replaceAllCase2);
6) Using split
int split = testString.split("\\.",-1).length-1;
System.out.println("split = " + split);
7) Using Java8 (case 1)
long java8 = testString.chars().filter(ch -> ch =='.').count();
System.out.println("java8 = " + java8);
8) Using Java8 (case 2), may be better for unicode than case 1
long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();
System.out.println("java8 (second case) = " + java8Case2);
9) Using StringTokenizer
int stringTokenizer = new StringTokenizer(" " +testString + " ", ".").countTokens()-1;
System.out.println("stringTokenizer = " + stringTokenizer);