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

//    題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
    //這裏可以使用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;

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章