判斷字符串中數字,空格,字母以及其他字符數量


//    題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
    //這里可以使用Character的一些方法更方便的判斷
    public static Map<String, Integer> method7(String str) {
        Map<String, Integer> result = new HashMap<>();
        char[] chars = str.toCharArray();
        int dig = 0;//數字計數
        int blank = 0;//空格
        int word = 0;//字母
        int other = 0;//其他字符
        for (char ch : chars) {
            if (Character.isLetter(ch)) {
                word++;
            } else if (Character.isDigit(ch)) {
                dig++;
            } else if (Character.isSpaceChar(ch)) {
                blank++;
            } else {
                other++;
            }
        }
        result.put("dig", dig);
        result.put("blank", blank);
        result.put("word", word);
        result.put("other", other);
        return result;

    }

 


免責聲明!

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



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