1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
public class Test15 { public static void main(String[] args) { String s = "1239586838923173478943890234092"; long nanos = System.nanoTime(); countChars1(s); System.out.println("\n for+for运行时间(纳秒):" + (System.nanoTime()-nanos));
System.out.println("-------------------------"); nanos = System.nanoTime(); countChars2(s); System.out.println("\n replace运行时间(纳秒):" + (System.nanoTime()-nanos));
System.out.println("-------------------------"); nanos = System.nanoTime(); countChars3(s); System.out.println("\n int[10]运行时间(纳秒):" + (System.nanoTime()-nanos)); System.out.println("-------------------------"); nanos = System.nanoTime(); countChars4(s); System.out.println("\n regex运行时间(纳秒):" + (System.nanoTime()-nanos));
} 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) { 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), ""); 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()); } } }
|