【JAVA练习题】六、字符统计 || ASCII

题目

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

分析

利用ASCII码值进行区分

package com.practice.java;

import java.util.Scanner;

/**
 * @author CT
 * @create 2021-05-27 21:21
 * @data 2021/5/27 - 21:21
 */
public class count_word {
    /**
     * 【程序7】
     * 题目:输入一行字符,分别统计出其英文字母、空格、数字和其它字符的个数。
     */
    public static void main(String[] args) {
        System.out.println("请输入字符串:" );
        Scanner scanner=new Scanner(System.in);
        scanner.useDelimiter("\n");
        String tmpStr = scanner.next();
        classify(tmpStr);
    }

    public static void classify(String str){
        char[] strArr = str.toCharArray();
        int num1 = 0;  //字母
        String num1Str = "";
        int num2 = 0;  //数字
        String num2Str = "";
        int space = 0; //空格
        String spaceStr = "";
        int other = 0; //其他
        String otherStr = "";
        for (int i = 0; i < strArr.length ; i++) {
            int ascii = (int)strArr[i];
            if( 48<= ascii && ascii <= 57){
                num2 = num2 + 1;
                num2Str = num2Str +strArr[i] +" ";
            }else if(ascii == 32){
                space = space +1;
            }else if((65<= ascii && ascii <= 90) || (97 <= ascii && ascii <=  122)){
                num1 = num1 + 1;
                num1Str = num1Str +strArr[i] +" ";
            }else{
                other = other + 1;
                otherStr = otherStr +strArr[i] +" ";
            }
        }
        System.out.println("存在字母个数:" + num1);
        System.out.println("存在字母如下:" + num1Str);

        System.out.println("存在数字个数:" + num2);
        System.out.println("存在数字如下:" + num2Str);

        System.out.println("存在空格个数:" + space);

        System.out.println("存在其他个数:" + other);
        System.out.println("存在其他如下:" + otherStr);

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值