輸入一行字符,分別統計出包含英文字母、空格、數字和其它字符的個數

題目描述

輸入一行字符,分別統計出包含英文字母、空格、數字和其它字符的個數。

輸入描述

輸入一行字符串,能夠有空格

輸出描述

統計其中英文字符,空格字符,數字字符,其餘字符的個數

輸入例子

1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\\/;p0-=\\][

輸出例子

26
3
10
12

算法實現

import java.util.Scanner;

/**
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            System.out.print(count(input));
        }

        scanner.close();
    }

    private static String count(String s) {
        int[] result = new int[4];

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
                result[0]++;
            } else if (c == ' ') {
                result[1]++;
            } else if (c >= '0' && c <= '9') {
                result[2]++;
            } else {
                result[3]++;
            }
        }

        StringBuilder builder = new StringBuilder();
        for (int i : result) {
            builder.append(i).append('\n');
        }

        return builder.toString();
    }
}
相關文章
相關標籤/搜索