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

输入一行字符,分别统计出其英文字母、空格、数字和其它字符的个数。
做这道题的方法不止一个,在这里,我用的方法是:将字符串转换为字符数组,然后对字符数组进行遍历统计。
有其他的方法欢迎交流!
代码:
import java.util.Scanner;

public class 统计 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.print("请输入字符:");
        String s=sc.nextLine();//将一行字符转化为字符串
        sc.close();
        count(s);
    }
    private static void count(String s){
        String a="[\u4e00-\u9fa5]";//汉字
        String b="[a-zA-Z]";
        String c="[0-9]";
        String d="\\s";//空格
        int countChinese=0;
        int countLetter=0;
        int countNumber=0;
        int conutSpace=0;
        int countOther=0;
        char[] array_Char=s.toCharArray();//将字符串转换为字符数组
        String[] array_String=new String[array_Char.length];//汉字只能作为字符串处理
        for(int i=0;i<array_Char.length;i++)
            array_String[i]=String.valueOf(array_Char[i]);
        //遍历字符串数组中的元素
        for(String s1:array_String) {
            if (s1.matches(a))
                countChinese++;
            else if (s1.matches(b))
                countLetter++;
            else if (s1.matches(c))
                countNumber++;
            else if (s1.matches(c))
                conutSpace++;
            else if(s1.matches(d))
                conutSpace++;
            else
                countOther++;
        }
        System.out.println("输入的汉字个数:"+countChinese);
        System.out.println("输入的字母个数:"+countLetter);
        System.out.println("输入的数字个数:"+countNumber);
        System.out.println("输入的空格个数:"+conutSpace);
        System.out.println("输入的其它字符个数:"+countOther);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑶台月下逢

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值