我想打一个打印的话,该号码的程序启动以大写字母。所以我做了两个弦str1 = "The deed is done"
和str2 = "My name is Bond, JAMES Bond"
。对于第一个字符串,它打印了1,这正是我想要的。但是对于第二个,因为JAMES
大写,所以它打印8而不是4 。
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;
}
到目前为止,这就是我所拥有的。我将如何做到这一点,以便不计入该单词中的其他字母?
您应该检查输入字符串中每个单词的第一个字符,而不是输入字符串中的所有字符。
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句