統計字符串中每個字符出現的次數


package LESSON11;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class exercise1 {
    /**
    使用Scanner從控制台讀取一個字符串,統計字符串中每個字符出現的次數
     */
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("請輸入一個字符串");
        String str=sc.nextLine();
        char ch[]=str.toCharArray();
        HashMap<Character, Integer> map=new HashMap();
//        for (int i = 0; i < ch.length; i++) { 
//            int count=1;
//            for (int j = i+1; j < ch.length; j++) {
//                if(ch[i]==ch[j]){
//                    count++;    //這樣寫最后相同的鍵的值會被覆蓋,所有的value都為1            
//                }    
//                
//            }
//            map.put(ch[i], count);        
//        }    
        //abcda
        int num=0;
        for (int i = 0; i < ch.length; i++) {
            if(!map.containsKey(ch[i])){//判斷集合中是否不包含某個字符
                num=1;                
            }else{
                num=map.get(ch[i]);//獲取該字符已經出現的次數
                num++;                                
            }
            map.put(ch[i], num);//每次循環都會存儲到map集合中            
        }
        System.out.println(map);                                                                                        
    }
}

運行結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM