繁体   English   中英

如何在Java中计算字符串中的大写单词?

[英]How to count uppercase words in a string in Java?

我需要计算字符串中大写单词的总数,但如果不涉及复杂的 if 语句和检查,我就无法弄清楚如何做到这一点。

我试过写下这样的东西:

private int uppercaseWordsCount(String input){
    count = 0;
    String[] ss = input.split("\\s");
    for (String s: ss){
        //???
        }

    }

    return count;

}

而且我仍然不知道满足我需要的良好条件。 问题是我必须处理整个单词(出于该方法的目的,像感叹号这样的特殊字符算作大写字符)而不是单个字符,因为我正在编写的系统的其余部分已经这样做了。

您可以通过split()调用拆分每个字符串,就像您目前为获取每个单词所做的那样。 此时,您可以选择如何处理比较每个单词以确定它们是否为大写。

将您的字符串与大写版本进行比较

您还可以使用toUpperCase()方法将字符串与其等效的大写字母进行比较并相应地递增

// The string is the same as an upper-cased version of itself
if(s.equals(s.toUpperCase())){
     // Then increment your count
     count++;
}

根据正则表达式检查字符串

您还可以使用正则表达式通过matches()方法查看字符串中的所有字符是否都是大写的:

// Increment your count if the string consists of only uppercase characters
if(s.matches("^[A-Z]+$")){
     count++;
}

这是如何使用 java 8 做到这一点

public static long countUpperCaseWord(String input) {
  // your object must be not null
  Objects.requireNonNull(input);

  // new stream of the array returned by the split call on input string
  return Stream.of(input.split("\\s")) 
               // we create a second stream that match the predicate passed throw the method filter
               .filter(word -> word.equals(word.toUpperCase())) 
               // finally we want to count how many words match this predicate
               .count();
}

如果需要计算条目中的大写字母:

  public static long countUpperCase(String input) {

     return input.chars()
                 .map(i -> (char) i)
                 .filter(c -> Character.isUpperCase(c))
                 .count();
  }

如果你想使用更多泛型代码来改进它,你可以这样写:

 public static long countWordsUsingPredicate(String input, Predicate<String> predicate) {
    Objects.requireNonNull(input);

    return Stream.of(input.split("\\s")) 
                 .filter(predicate) 
                 .count();
}

并通过将谓词作为 lambda 表达式传递给方法来调用此 util 方法:

countUpperCaseWord("THIS BREAK", word -> word.equals(word.toUpperCase()))

简单的方法是定义您的“大写单词模式”,然后对其进行匹配计数:

Pattern pattern = Pattern.compile("\b[A-Z\!\@\$\%\^\&\*\(\)\[\]]\S+\b");
Matcher matcher = pattern.matcher("Your Input String Here");
int count = 0;
while (matcher.find()) { count++; }
System.out.printf("%d uppercase words.%n", count);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM