天天看點

java統計字元串中出現最多_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納秒不穩定

}

public static void countChars1(String s) {

StringBuilder sb = new StringBuilder();

for (int i = 0; i < s.length(); i++) {

int count = 0;

Character ch = new Character(s.charAt(i));

if (sb.indexOf(ch.toString()) >= 0) { // 利用StringBuilder的indexOf()方法查重

continue;

}

for (int j = 0; j < s.length(); j++) {

if (ch == s.charAt(j)) {

sb.append(ch);

count++;

}

}

System.out.println(ch + "出現次數:" + count);

}

}

public static void countChars2(String s) {

for (int i = 0; i < 10; i++) {

String str = s.replace(String.valueOf(i), ""); // 将1-9單個相同的數字替換出來,剩下的儲存

System.out.println(i + "出現次數:" + (s.length()-str.length()));

}

}

public static void countChars3(String s) {

int[] c = new int[10];

for(int i = 0 ; i < s.length(); i++){

char ch = s.charAt(i);

int a = ch-48;

c[a]++;

}

for (int i = 0; i < c.length; i++) {

System.out.println(i + "出現次數:" + c[i]);

}

}

public static void countChars4(String s) {

for (int i = 0; i < 10; i++) {

String str2 = s.replace("[^"+i+"]", "");

System.out.println(i + "出現次數:" + str2.length());

}

}

}