java中如何计算以大写字母开头的单词?

Ano*_*ous 1 java count cpu-word uppercase

我想打一个打印的话,该号码的程序启动以大写字母。所以我做了两个字符串str1 = "The deed is done"str2 = "My name is Bond, JAMES Bond"。对于第一个字符串,它打印了我想要的 1。但是对于第二个,它打印 8 而不是 4,因为它JAMES是大写的。


    public static void main(String[] args){
        String str1 = "The deed is done";
        String str2 = "My name is Bond, JAMES Bond";

        System.out.println(uppercase(str2));
    }

    public static int uppercase(String str){
        int cnt = 0;

        for(int i = 0; i < str.length(); i++){
            if(Character.isUpperCase(str.charAt(i)))
                cnt++;
        }

        return cnt;
    }

Run Code Online (Sandbox Code Playgroud)

这就是我到目前为止所拥有的。我如何才能不计算该单词中的其他字母?

War*_*ard 6

您应该检查输入字符串中每个单词第一个字符,而不是输入字符串的所有字符

public static int uppercase(String str){
    int cnt = 0;

    String[] words = str.split(" ");

    for(int i = 0; i < words.length; i++){
        if(Character.isUpperCase(words[i].charAt(0)))
            cnt++;
    }

    return cnt;
}
Run Code Online (Sandbox Code Playgroud)

一种更“声明性的方法”可以使用 Stream

public static long uppercase2(String str){
    return Arrays.stream(str.split(" "))
            .map(word -> word.charAt(0))
            .filter(Character::isUpperCase)
            .count();
}
Run Code Online (Sandbox Code Playgroud)

  • 关于为什么投反对票的任何反馈?我渴望改进/纠正这个答案 (2认同)