本文實(shí)例講述了Java編程實(shí)現(xiàn)統(tǒng)計(jì)一個字符串中各個字符出現(xiàn)次數(shù)的方法。分享給大家供大家參考,具體如下:
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 { //統(tǒng)計(jì)一個字符串中相應(yīng)字符出現(xiàn)的次數(shù) public static void main(String[] args) { // System.out.println( "服務(wù)器之家測試結(jié)果:" ); String s = "aagfagdlkerjgavpofjmvglk我是你的" ; //調(diào)用自定義方法來 統(tǒng)計(jì)相應(yīng)字符出現(xiàn)的次數(shù) method(s); } private static void method(String s) { //定義 一個容器 TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(); //將這TreeMap中的key全部取出來,然后儲存到set集合中去 Set<Character> st = tm.keySet(); //將所需要統(tǒng)計(jì)的字符串轉(zhuǎn)換成一個字符數(shù)組 char [] c = s.toCharArray(); //通過for循環(huán)逐一統(tǒng)計(jì)每個字符出現(xiàn)的次數(shù) 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 ); } } //調(diào)用自定義方法在控制臺上輸出統(tǒng)計(jì)信息 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)+ ")" ); } } } |
運(yùn)行結(jié)果:
希望本文所述對大家java程序設(shè)計(jì)有所幫助。
原文鏈接:http://blog.csdn.net/zl18603543572/article/details/46567685