题解 | #统计大写字母个数#

统计大写字母个数

https://www.nowcoder.com/practice/434414efe5ea48e5b06ebf2b35434a9c

两种方式:

方式1,使用正则验证,直接剔除 A ~ Z

方式2,循环遍历,遍历每个字符,属于 A ~ Z 之间的循环计数

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        // System.out.println(function1(s));
        char[] chars = s.toCharArray();
        System.out.println(function2(chars));
    }

    /**
        方式1:使用正则,把A-Z全替换掉,然后老长度 - 新长度得到字符数
     */
    private static int function1(String s) {
        int olen = s.length();
        int nlen = s.replaceAll("[A-Z]", "").length();
        return olen - nlen;
    }

    /**
        方式2:循环遍历,查找每个字符是否在 A-Z 的 ascii 码之间
     */
    private static int function2(char[] chars) {
        int count = 0;
        for(char c: chars) {
            if(isUpperCase(c)) count++ ;
        }
        return count;
    }


    // 验证是否大写字母
    private static boolean isUpperCase(char c) {
        return c >= 'A' && c <= 'Z';
    }
}

全部评论

相关推荐

allin秋招的大菠萝很爱交友:后续,已拿offer ~查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务