#需求:
輸入字符:abcdeabcde 輸出:a(2)b(2)c(2)d(2)e(2);
#分析:
##步驟:
A:輸入一個字符串
B:定義一個TreeMap集合,健:Charater 值:Integer
C:把字符串轉(zhuǎn)為字符數(shù)組
D:遍歷字符數(shù)組,得到每一個字符
E:剛得到的字符作為鍵到集合中去找,看返回值,是null說明該字符在集合中不存在,將該字符作為鍵添加進集合中,并將其值置為1
F:定義字符串緩沖區(qū)
G:遍歷集合得到鍵和值,按照要求拼接
H:將緩沖區(qū)中的字符串輸出
完整代碼:
import java.util.TreeMap;
import java.util.Set;
import java.util.Scanner;
public class TreeMapDemo{
public static void main(String[] args){
//A:輸入一個字符串
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個字符串:");
String line = sc.nextLine();
//B:定義一個TreeMap集合,鍵:Charater 值:Integer
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
//C:將字符串轉(zhuǎn)換為字符數(shù)組
char[] chs = line.toCharArray();
//D:遍歷字符串?dāng)?shù)組,得到每一個字符
for(char ch:chs){
Integer i = tm.get(ch);
if(i == null){
//該字符作為鍵去集合中找,如果返回值是null,說明該鍵不存在,將該字符作為鍵,將其值置為1
tm.put(ch,1);
}else{
//如果不是null,則將其值加1,然后存放
i++;
tm.put(ch,i);
}
}
//E:定義一個字符串緩沖區(qū)
StringBuffer sb = new StringBuffer();
//F:按照指定的格式拼接
Set<Character> set = tm.keySet();
for(Character key:set){
Integer value = tm.get(key);
sb.append(key).append("(").append(value).append(")");
}
//G:將其轉(zhuǎn)換為字符串
String result = sb.toString();
//H:將緩沖區(qū)的字符串輸出
System.out.println("result:"+result);
}
}