I want to change a String so that all the uppercase characters become lowercase, and all the lower case characters become uppercase. Number characters are just ignored.
I think the simplest solution to understand would be something like:
public static String reverseCase(String text) {
StringBuilder sb = new StringBuilder();
for (char c : text.toCharArray())
sb.append((Character.isUpperCase(c)) ?
Character.toLowerCase(c) :
(Character.isLowerCase(c) ? Character.isUpperCase(c) : c));
return sb.toString();
}
I think you can read through this easier and StringBuilder has an append(char) method anyways + Character.toUpperCase and toLowerCase are both just static methods. I just felt bad that the only StringBuilder example had ascii index arithmetics included as well.
For those who don't like ternary expressions, here's the equivalent:
public static String reverseCase(String text) {
StringBuilder sb = new StringBuilder();
for (char c : text.toCharArray())
if (Character.isUpperCase(c))
c = Character.toLowerCase(c);
else if (Character.isLowerCase(c))
c = Character.toUpperCase(c);
sb.append(c);
return sb.toString();
}