重要練習:將字符串中的字母按如下格式顯示:
a(1)b(2)......
代碼及思路如下:
/*獲取字符串中字母的次數(shù),并打印出如下格式a(1)b(2)c(3)......思路:先定義一個方法,將該功能進行封裝.1.首先將字符串轉換成字符數(shù)組 方法是toCharArray();2.定義一個map容器用來接收每個字符, 因為結果是有序的可以使用TreeMap3.遍歷字符數(shù)組 for循環(huán). 將字母作為 鍵 去map集合中去查詢該字母,如果返回null,說明map集合中沒有該字母,那么將該字母和1存入到map集合中去, 如果返回的不是null,說明此時的map集合中已經(jīng)有了該字母,那么在map集合中該字母對應的次數(shù)自增1,然后將該字母和自增后的次數(shù)存入到map集合中去. 存入后會覆蓋原先的次數(shù).3將map集合中的數(shù)據(jù)按指定形式打印出來 指定形式: 1.定義一個容器.StringBuilder緩沖區(qū)可以存放任何數(shù)據(jù)的形式,通過Map集合的KeySet方法或者entrySet方法獲取map集合中的鍵值或者其映射關系 通過keySet的get(key)方法獲取map集合中的value 或者entrySet的方法getKey()方法和getValue()方法獲取對應的鍵和值. 2.最后將鍵和值通過 StringBuilder的append方法添加進緩沖區(qū),并打印. 由于StringBuilder和String不是同一個類,因此return sb的時候需要 寫上toString--->return sb.toString();*/import java.util.*;class MapCharTest{ public static void main(String [] args) { String s = myCharCount("aabbccddedsf"); sop(s); } public static String myCharCount(String str) { //將字符串轉換成字符數(shù)組 char [] chs = str.toCharArray(); //定義一個map集合 TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(); //遍歷字符數(shù)組 for(int x = 0; x<chs.length; x++) { //將字母作為 鍵 去查找對應的 值 Integer value = tm.get(chs[x]); //去除不是字母的其他字符. if(!(chs[x]>='a'&&chs[x]<='z' || chs[x]>='A'&& chs[x]<='Z')) continue; //判斷 值 是否存在 if(value==null) tm.put(chs[x],1); else { value = value+1; tm.put(chs[x],value); } } // sop(tm); //創(chuàng)建一個緩沖區(qū) StringBuilder sb = new StringBuilder(); /* //第一種Map取出方式 keySet方法 Set<Character> keySet = tm.keySet(); 迭代set集合中的鍵集 Iterator<Character> it = keySet.iterator(); while(it.hasNext()) { Character key = it.next(); //獲取鍵 Integer value = tm.get(key); //通過鍵獲取對應的 值 sb.append(key+"("+value+")"); //將鍵和值添加進緩沖區(qū)中 } */ //Map集合第二種取出方式:entrySet Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet(); Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator(); while(it.hasNext()) { Map.Entry<Character,Integer> me = it.next(); Character key = me.getKey(); Integer value = me.getValue(); sb.append(key+"("+value+")"); } return sb.toString(); //將StringBuilder按String形式打印出來. } public static void sop(Object obj) { System.out.PRintln(obj); }}
新聞熱點
疑難解答