黑马程序员 【】java学习之路——计算字符串中字母出现的次数

来源:互联网 发布:北京php培训公司排名 编辑:程序博客网 时间:2024/05/21 10:16

                                          -------android培训、java培训、期待与您交流! ----------

问题:给定一个字符串,计算每个字母在字符串中出现的次数,要求打印结果为:a(2) b(3).。。。。。。

import java.util.*;public class CharCount {public static void main(String[] args) {String str = "aabscdkjsfld";count(str);}public static void count(String str){TreeMap<Character,Integer> tm =newTreeMap<Character,Integer>();char [] chs = str.toCharArray();for (int i = 0; i < chs.length; i++) {Integer value = tm.get(chs[i]);if (value==null) {tm.put(chs[i], 1);}else{value = value+1;tm.put(chs[i], value);}}Set<Character> st = tm.keySet();Iterator<Character> it = st.iterator();while(it.hasNext()){char key = it.next();Integer value = tm.get(key);System.out.print(key+"("+value+")  ");}}}


0 0