- package fuxi1;
- import java.util.Iterator;import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- /**
- * 题目:"jakldfjasldfj"获取一个字符串中每个字母出现的次数。
- * 希望打印的结果为:a(2)d(1)...
- * 思路:由打印结果可知,这是键值存在的数据,要用到Map集合。而且字母是按顺序排列的要用到TreeMap集合进行排序。
- *@author XiaLei
- */
- public class Day16Test6 {
- public static void main(String[] args) {
- String str = "jakldfj66asldfj";
- char[] arr = str.toCharArray();//将字符串变成字符数组。
- TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
- int count = 0;
- for(int x = 0;x<arr.length;x++){
- char ch = arr[x];
- String reg = "[a-zA-Z]";//利用正则表达式判断元素是否为字母。
- if(!(String.valueOf(ch).matches(reg)))
- continue;
-
- if(tm.containsKey(ch)){
- Integer value = tm.get(ch);
- count = value;//如果有相同的键(字母)则将对应的值赋给count。
- }
- count++;
- tm.put(ch,count);
- count = 0;//将计数器清零,这一点很容易出错,应牢记。
- }
- Set<Map.Entry<Character,Integer>> s = tm.entrySet();
- for(Iterator<Map.Entry<Character,Integer>> it = s.iterator(); it.hasNext();){
- Map.Entry<Character,Integer> me = it.next();
- Character key = me.getKey();
- Integer value = me.getValue();
- System.out.print(key+"("+value+")");
- }
- }
- }
复制代码 |
|