String類練習統計一個字符串中大小寫字母及數字字符個數


public class StringPractice {
    public static void main(String[] args) {
        //創建一個文本掃描器
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入一個字符串:");
        String str = sc.next();

        //定義三個變量用來統計大寫字母,小寫字母,數字的個數
        int bigCount = 0;
        int smallCount = 0;
        int numCount = 0;

        //遍歷字符串,對每個字符進行判斷
        for (int i = 0;i<str.length();i++){
            char chs = str.charAt(i);
            //如果
            if (chs >= 'A' && chs <= 'Z'){
                bigCount++;
            }else if (chs >= 'a' && chs <= 'z'){
                smallCount++;
            }else if (chs >= '0' && chs <= '9'){
                numCount++;
            }else {
                System.out.println("該字符"+chs+"非法");
            }
        }
        //輸出結果
        System.out.println("大寫字符:"+bigCount+"");
        System.out.println("小寫字符:"+smallCount+"");
        System.out.println("數字字符:"+numCount+"");


    }
}

 


免責聲明!

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



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