本文實例講述了Java編程實現統計一個字符串中各個字符出現次數的方法。分享給大家供大家參考,具體如下:
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
|
import java.util.Iterator; import java.util.Set; import java.util.TreeMap; public class TreeMapDemo { //統計一個字符串中相應字符出現的次數 public static void main(String[] args) { // System.out.println( "服務器之家測試結果:" ); String s = "aagfagdlkerjgavpofjmvglk我是你的" ; //調用自定義方法來 統計相應字符出現的次數 method(s); } private static void method(String s) { //定義 一個容器 TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(); //將這TreeMap中的key全部取出來,然后儲存到set集合中去 Set<Character> st = tm.keySet(); //將所需要統計的字符串轉換成一個字符數組 char [] c = s.toCharArray(); //通過for循環逐一統計每個字符出現的次數 for ( int x= 0 ;x<c.length;x++) { if (!st.contains(c[x])) { tm.put(c[x], 1 ); } else { tm.put(c[x], tm.get(c[x])+ 1 ); } } //調用自定義方法在控制臺上輸出統計信息 printMapDemo(tm); } private static void printMapDemo(TreeMap<Character, Integer> tm) { // TODO Auto-generated method stub Set<Character> st = tm.keySet(); Iterator<Character> ti = st.iterator(); for (;ti.hasNext();) { char key = ti.next(); System.out.println(key+ "(" +tm.get(key)+ ")" ); } } } |
運行結果:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/zl18603543572/article/details/46567685