Anacarnil Anacarnil - 7 months ago 19
Java Question

How to count uppercase words in a string in Java?

I need to count the total number of uppercase words in a string, but I just can't figure out how to do it without complex if statements and checks involved.

I've tried and written down something like this:

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

}

return count;

}


And I still have no clue about a good condition to match my need. The thing is I have to deal with whole words (special characters like exclamation marks count as uppercase characters for the purpose of the method) and not single characters, as the rest of the system I'm writing already does.

Answer

You could split each string via the split() call as you are currently doing to obtain each word. At this point, you have options with how you want to handle comparing each of the words to determine if they are uppercase.

Compare Your String to an Uppercase Version

You could also compare the string to its uppercase equivalent as well using the toUpperCase() method and increment accordingly

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

Check The String Against A Regular Expression

You could also use a regular expression to see if all of the characters within the string are uppercase via the matches() method :

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