算法(15)输入一串字符,分别统计出数字、英文字母、空格以及其它字符的个数

题目

输入一串字符,分别统计出数字、英文字母、空格以及其它字符的个数

代码实现:

public class WordCount {

    public static void main(String[] args) {
        System.out.print("输入一串字符:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();

        //将输入的字符串转为字符型数组
        char[] chars = s.toCharArray();
        System.out.println(Arrays.toString(chars));

        // 数字
        int num = 0;
        // 英文字母
        int letter = 0;
        // 空格
        int space = 0;
        // 其它
        int others = 0;

        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= 48 && chars[i] <= 57) {
                num++;
            } else if ((chars[i] >= 65 && chars[i] <= 90) || (chars[i] >= 97 && chars[i] <= 122)) {
                letter++;
            } else if (chars[i] == 32) {
                space++;
            } else {
                others++;
            }
        }
        System.out.println("数字:" + num + "个, 字母:" + letter + "个, 空格:"
                + space + "个, 其它:" + others + "个");
    }
}

测试结果:

输入一串字符串:helloworld Programmer
[h, e, l, l, o, w, o, r, l, d,  , P, r, o, g, r, a, m, m, e, r]
数字:0, 字母:20个, 空格:1个, 其它:0
发布了73 篇原创文章 · 获赞 796 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43570367/article/details/103332305