题解 | 判断各类型字符个数

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int numbers = 0;
        int words = 0;
        int space = 0;
        int other = 0;
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();

        //write your code here......
        for (int i = str.length() - 1; i >= 0; i--) {
            char c = str.charAt(i);
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                words++;
            } else if (c >= '0' && c <= '9') {
                numbers++;
            } else if (c == ' ') {
                space++;
            } else {
                other++;
            }
        }
        System.out.println("英文字母" + words + "数字" + numbers + "空格" +
                           space + "其他" + other);
    }
}

两种解法

for (int i = str.length() - 1; i >= 0; i--) {
            char c = str.charAt(i);
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                words++;
            } else if (c >= '0' && c <= '9') {
                numbers++;
            } else if (c == ' ') {
                space++;
            } else {
                other++;
            }
        }
for(int i=str.length()-1;i>=0;i--){
            char c=str.charAt(i);
            if(Character.isLetter(c)){
                words++;
            }else if(Character.isDigit(c)){
                numbers++;
            }else if(Character.isSpaceChar(c)){
                space++;
            }else{
                other++;
            }
        }

全部评论

相关推荐

AAA专业长城贴瓷砖刘大爷:这样的简历我会直接丢进垃圾桶,花里胡哨的
点赞 评论 收藏
分享
野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务