用集合去統計字符串中每個字符串出現的次數
-
題目:鍵盤錄入一個字符串,要求統計字符串中每個字符串出現的次數。
舉例:鍵盤錄入“aababcabcdabcde” 在控制台輸出:“a(5)b(4)c(3)d(2)e(1)”
public class HashMapDemo2 {
public static void main(String[] args) {
//鍵盤輸入一個字符串
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個字符串");
String line = sc.nextLine();
//創建HashMap集合,鍵是Character,值是Integer
TreeMap<Character, Integer> hm = new TreeMap<>();
//遍歷字符串,得到每一個字符
for (int i = 0; i < line.length(); i++) {
char key = line.charAt(i);
//拿得到的每一個字符作為鍵到HashMap集合種去找對應的值,看其返回值
Integer value = hm.get(key);
if (value == null){
//如果返回值是null,說明該字符在HashMap種不存在,就把該字符作為鍵,1作為值存儲
hm.put(key,1);
}else{
//如果返回值不是null,說明該字符在HashMap集合中存在,把該值+1,然后從新存儲該字符和對應的值
value++;
hm.put(key,value);
}
}
//遍歷HashMap集合,得到鍵和值,按照要求進行拼接
StringBuilder sb = new StringBuilder();
Set<Character> keySet = hm.keySet();
for (Character key : keySet){
Integer value = hm.get(key);
sb.append(key).append("(").append(value).append(")");
}
String result = sb.toString();
//輸出結果
System.out.println(result);
}
}