题解 | #统计字符#

统计字符

https://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        char[] chars = str.toCharArray();
        int number = 0;
        int letter = 0;
        int space = 0;
        int other = 0;
        for (char c : chars) {
            // 最粗暴的实现方式
//            if(c >= '0' && c <='9') {
//                number++;
//            } else if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
//                letter++;
//            } else if( c == ' ') {
//                space++;
//            } else {
//                other++;
//            }
            // 使用Character自带的工具类
            if (Character.isLetter(c)) {
                letter++;
            } else if (Character.isSpaceChar(c)) {
                space++;
            } else if (Character.isDigit(c)) {
                number++;
            } else {
                other++;
            }
        }
        System.out.println(letter);
        System.out.println(space);
        System.out.println(number);
        System.out.println(other);
    }
}

全部评论

相关推荐

06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务