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

How do I count the words that start with an uppercase letter in java?

我想制作一个程序,打印 START 大写字母的字数。所以我做了两个字符串 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;
    }

这就是我目前所拥有的。我该怎么做才能不计算该词中的其他字母?

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

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;
}

更多'declarative approach'可以使用Stream

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

一个很好的方法是使用正则表达式:\b[A-Z] 测试单词边界后出现的大写字母,这样我们就可以找到所有匹配项并计算它们。

> import java.util.regex.*;
> Pattern p = Pattern.compile("\b[A-Z]");
> Matcher m = p.matcher("Hi, this is Stack Overflow.");
> int c = 0;
> while(m.find()) { c++; }
> c
3
      String str1 = "The deed is done";
      String str2 = "My name is Bond, JAMES Bond";

      System.out.println(upperCaseCount(str1));
      System.out.println(upperCaseCount(str2));


     public static int upperCaseCount(String s) {
       int count = 0;
       // append a space to cater for empty string and
       // use regex to split on one or more spaces.
       for (String word : (s + " ").split("\s+")) {
          if (Character.isUpperCase(word.charAt(0))) {
            count++;
          }
       }
       return count;
     }