我想制作一个程序,打印带有大写字母的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;
}
这就是我到目前为止所拥有的。我将如何做到这一点,以便不计入该单词中的其他字母?
您应检查输入字符串中每个word的first字符,而不是输入字符串的all character。
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();
}
[做到这一点的一种好方法是使用正则表达式:\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 lineOfCurrencies = "USD JPY AUD SGD HKD CAD CHF GBP EURO INR";
String[] currencies = lineOfCurrencies.split(" ");
System.out.println("input string words separated by whitespace: " + lineOfCurrencies);
System.out.println("output string: " + Arrays.toString(currencies));
Output:
input string words separated by whitespace: USD JPY AUD SGD HKD CAD CHF GBP EURO INR
output string: [USD, JPY, AUD, SGD, HKD, CAD, CHF, GBP, EURO, INR]
然后,您可以检查元素的第一个字符是否为大写。根据您的问题,您已经知道如何检查大写字母。只需遍历数组就可以了。
执行以下操作:
public class Main {
public static void main(String[] args) {
String str1 = "The deed is done";
String str2 = "My name is Bond, JAMES Bond";
System.out.println(firstLetterUpperCaseCount(str1));
System.out.println(firstLetterUpperCaseCount(str2));
}
public static int firstLetterUpperCaseCount(String str) {
String[] strArr=str.split(" ");
int cnt = 0;
for (int i = 0; i < strArr.length; i++) {
if (Character.isUpperCase(strArr[i].charAt(0)))
cnt++;
}
return cnt;
}
}
输出:
1
4