【算法006】统计字符串中英文字母、空格、数字和其它字符的个数

输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

package com.example.chyer.demo;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        int abccount = 0;
        int spacecount = 0;
        int numcount = 0;
        int othercount = 0;
        Scanner input = new Scanner(System.in);
        String toString = input.nextLine();
        char[] ch = toString.toCharArray();

        for (int i = 0; i < ch.length; i++) {
            // 汉字也算letter
            if (Character.isLetter(ch[i])) {
                abccount++;
            } else if (Character.isDigit(ch[i])) {
                numcount++;
            } else if (Character.isSpaceChar(ch[i])) {
                spacecount++;
            } else {
                othercount++;
            }
        }
        System.out.println("abc:" + abccount);
        System.out.println("space:" + spacecount);
        System.out.println("num:" + numcount);
        System.out.println("other:" + othercount);
    }
}

运行结果:

发布了29 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/chyercn/article/details/103230316
今日推荐