Java中4种⽅法统计字符串中字符出现次数-优劣分析
1. 4种⽅法思路
统计字符串中所有字符出现的次数的 4 种⽅法,总结如下:
countChars1() ⽅法使⽤ for-for双重循环,逐个计数、检查重复;
countChars2() ⽅法使⽤String的replace⽅法替换出相同字符,保存剩下的字符组成的字符串,最后长度相减,得出每个字符次数;
countChars3() ⽅法使⽤new int[10]数组,以下标作为要统计的数字字符,以元素作为计数器进⾏计数;
countChars4() ⽅法使⽤regex正则表达式匹配,直接替换出相同的字符组成新的字符串,新字符串的长度即⽬标替换字符的数量
2. 运⾏速度⽐较
① countChars3 最快,约20~50w纳秒
② countChars4 其次,约50-80w纳秒
③ countChars1 再其次,约60-90w纳秒
④ countChars3 较慢,约220-250w纳秒
(运⾏次数超过10次,⼤约数据)
原因分析:内存空间分配/拷贝的频率和循环次数会影响最终运⾏时间。
3. 实⽤功能⽐较
countChars2/3/4 ⽅法只能对纯数字组成的字符串进⾏字符统计;
countChars1 ⽅法可以针对任意字符串进⾏字符统计。
4. 源码:4种⽅法含部分注释
码来!!!
/**
*  给定字符串,统计每个字符出现的次数
*/
public class Test15 {
public static void main(String[] args) {
String s = "1239586838923173478943890234092";
long nanos = System.nanoTime();
countChars1(s); // for+for 逐个计数、查重
System.out.println("\n for+for运⾏时间(纳秒):" +  (System.nanoTime()-nanos)); // 约79w纳秒
System.out.println("-------------------------");
nanos = System.nanoTime();
countChars2(s); // replace() 重复的替换为空,两个字符串长度相减
System.out.println("\n replace运⾏时间(纳秒):" +  (System.nanoTime()-nanos)); // 约250w纳秒
System.out.println("-------------------------");
nanos = System.nanoTime();
countChars3(s); // new int[10] 使⽤0-9下标作为数字,元素作计数
System.out.println("\n int[10]运⾏时间(纳秒):" +  (System.nanoTime()-nanos)); // 约39w纳秒
System.out.println("-------------------------");
nanos = System.nanoTime();
countChars4(s); // regex 正则匹配直接替换出相同的字符组成字符串,长度即数量
System.out.println("\n regex运⾏时间(纳秒):" +  (System.nanoTime()-nanos)); // 约50w~80w纳秒不稳定
java replace方法
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。