【问题标题】:How do I count the words that start with an uppercase letter in java?如何计算java中以大写字母开头的单词?
【发布时间】:2019-12-17 21:17:07
【问题描述】:

我想制作一个程序,打印出 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;
    }

这就是我目前所拥有的。我怎样才能使该单词中的其他字母不被计算在内?

【问题讨论】:

    标签: java count word uppercase


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 对为什么投反对票有任何反馈吗?我渴望改进/纠正这个答案
    • 我运行了你的代码,它运行良好,我取消了反对票,不知道为什么它被反对了。我能看到的唯一原因是可能需要更多解释,但我认为这值得在这里发表评论而不是投反对票。
    • 这个确实有效,不知道为什么不赞成。您能解释一下拆分工作以及为什么将其放入数组中吗?
    • 我会做的稍有不同。 regex 用于多个空格并将split 合并到增强的for loop 中,并且不使用索引。但它仍然有效。这是团结的 +1。
    【解决方案2】:
          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;
         }
    

    【讨论】:

      【解决方案3】:

      一个很好的方法是使用正则表达式:\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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 2021-03-12
        • 2020-07-28
        • 2023-02-21
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        相关资源
        最近更新 更多