本文實例講述了Java編程實現統計一個字符串中各個字符出現次數的方法。分享給大家供大家參考,具體如下:
import java.util.Iterator;import java.util.Set;import java.util.TreeMap;public class TreeMapDemo{//統計一個字符串中相應字符出現的次數 public static void main(String[] args) { // System.out.println("VeVb武林網測試結果:"); 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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選