1. 程式人生 > >任意輸入一串字符串,求該字符串中字符的出現次數並打印出來,如輸入“bcaba”輸出:b 2 c 1 a 2

任意輸入一串字符串,求該字符串中字符的出現次數並打印出來,如輸入“bcaba”輸出:b 2 c 1 a 2

str ner ray view 方法 打印 contain 返回 play

前言:其實我還是有點不懂,有點郁悶了,算了直接把代碼放上去把。

方法一:

技術分享
Scanner input=new Scanner(System.in);
        System.out.println("請輸入一個字符");
        String str=input.next();
        
        char[] strChar=str.toCharArray();
        //聲明集合,把之存在集合中
        Map<Character,Integer> map=new HashMap<>();
        
        
for(int i=0;i<strChar.length;i++){ if(map.containsKey(strChar[i])){ map.put(strChar[i],map.get(strChar[i])+1); }else{ map.put(strChar[i],1); } } for(Map.Entry<Character, Integer> entry: map.entrySet()){ System.out.println(entry.getKey()
+":"+entry.getValue()); } input.close();
View Code

方法二:

技術分享
 1 Scanner input=new Scanner(System.in);
 2         System.out.println("請輸入一個字符");
 3         String str=input.next();
 4         
 5         
 6         //聲明集合,把之存在集合中
 7         Map<Character,Integer> map=new HashMap<>();
8 9 for(int i=0;i<str.length();i++){ 10 if(map.containsKey(str.charAt(i))){//如果此映射將一個或多個鍵映射到指定值,則返回 true。 11 map.put(str.charAt(i),map.get(str.charAt(i))+1); 12 }else{ 13 map.put(str.charAt(i),1); 14 } 15 } 16 17 for(Map.Entry<Character, Integer> entry: map.entrySet()){ 18 System.out.println(entry.getKey()+":"+entry.getValue()); 19 } 20 input.close();
View Code

任意輸入一串字符串,求該字符串中字符的出現次數並打印出來,如輸入“bcaba”輸出:b 2 c 1 a 2