I am trying to create a simple program that counts the uppercase characters in a String
by looping through each character and incrementing an accumulator variable if the character is uppercase. Here is my code:
String str = "JuSTin"; //3 uppercase characters
int upperCaseCount = 0; //increment each time an uppercase character is encountered
char character; //the current character
for(int i = 0; i < str.length(); i++)
{
character = str.charAt(i);
System.out.println(character); //Log all characters to console just to see what is going on
if(Character.isUpperCase(character))
upperCaseCount++;
i++;
}
System.out.println("Uppercase characters: " + upperCaseCount);
When ran this code outputs:
J
S
i
Uppercase characters: 2
What is causing this output? Where is the 'u' 'T' and 'n' in "JuSTin"? Why is upperCaseCount
equal to 2 and not 3?
Just as a complement information (for your learning-purpose), you can solve it in different ways using:
- lambda,
- 'classic' for loop,
- loop construct introduced in Java 7,
- regular expression,
- or forEach loop
Each of these ways have their own advantages or drawbacks.
With a lambda
public static long countUpperCase(final String str) {
return str
.chars() // get all chars from the argument
.filter(c -> Character.isUpperCase(c)) // filter only the uppercase
.count(); // count the uppercase
}
With a classic for loop
public static long countUpperCase(final String str) {
long counter = 0;
for(int i=0; i<str.length(); i++) {
if(Character.isUpperCase(str.charAt(i))) {
counter++;
}
}
return counter;
}
With new loop construct (Java 7 or higher)
public static long countUpperCase(final String str) {
long counter = 0;
for(final char c: str.toCharArray()) {
if(Character.isUpperCase(c)) {
counter++;
}
}
return counter;
}
There are already some explanation in other posts, e.g. Uppercase SO post
With a regular expression
public static long countUpperCase(final String str) {
// \p{L} matches a single code point in the category "letter"
// \p{L} matches all letters that are uppercase
return str.split("(?=\\p{Lu})").length;
}
If you are interesting to dig a bit deeper, have a look at this interesting PDF: Guide to Regexp
With a forEach loop
public static long countUpperCase(final String str) {
// the 'var' keyword can be used with Java 10 or higher
final var counter = new AtomicInteger(0);
// convert a string into a List<Character>
// Note that this is only applicable since Java 8 or higher
var chars = str
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
// count the number of uppercase letters
chars.forEach(c -> {
if(Character.isUpperCase(c)) {
counter.incrementAndGet();
}
});
return counter.get();
}