总结其他答案以及我所知道的使用单行符的所有方法:
String testString = "a.b.c.d";
1) 使用 Apache Commons
int apache = StringUtils.countMatches(testString, ".");
System.out.println("apache = " + apache);
2) 使用 Spring 框架的
int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, ".");
System.out.println("spring = " + spring);
3) 使用替换
int replace = testString.length() - testString.replace(".", "").length();
System.out.println("replace = " + replace);
4) 使用 replaceAll(案例 1)
int replaceAll = testString.replaceAll("[^.]", "").length();
System.out.println("replaceAll = " + replaceAll);
5) 使用 replaceAll(案例 2)
int replaceAllCase2 = testString.length() - testString.replaceAll("\\.", "").length();
System.out.println("replaceAll (second case) = " + replaceAllCase2);
6) 使用拆分
int split = testString.split("\\.",-1).length-1;
System.out.println("split = " + split);
7) 使用Java8(案例1)
long java8 = testString.chars().filter(ch -> ch =='.').count();
System.out.println("java8 = " + java8);
8) 使用 Java8(案例 2),对于 unicode 可能比案例 1 更好
long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();
System.out.println("java8 (second case) = " + java8Case2);
9) 使用 StringTokenizer
int stringTokenizer = new StringTokenizer(" " +testString + " ", ".").countTokens()-1;
System.out.println("stringTokenizer = " + stringTokenizer);
来自评论:小心 StringTokenizer,对于 abcd 它会起作用,但对于 a...bc...d 或 ...abcd 或 a....b... ...c.....d... 或等它不会起作用。它只是算数。字符之间只有一次
更多信息github
Perfomance test(使用JMH,模式=AverageTime,得分0.010优于0.351):
Benchmark Mode Cnt Score Error Units
1. countMatches avgt 5 0.010 ± 0.001 us/op
2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op
3. stringTokenizer avgt 5 0.028 ± 0.002 us/op
4. java8_1 avgt 5 0.077 ± 0.005 us/op
5. java8_2 avgt 5 0.078 ± 0.003 us/op
6. split avgt 5 0.137 ± 0.009 us/op
7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op
8. replace avgt 5 0.303 ± 0.034 us/op
9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op