How can I invert the case of a String in Java?
I guess there must be a way to iterate through the String and flip each character
Correct. The java.lang.Character
class provides you under each the isUpperCase()
method for that. Test on it and make use of the toLowerCase()
or toUpperCase()
methods depending on the outcome. Append the outcome of each to a StringBuilder
and you should be fine.
Apache Commons StringUtils has a swapCase method.
I don't believe there's anything built-in to do this (it's relatively unusual). This should do it though:
public static String reverseCase(String text)
{
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++)
{
char c = chars[i];
if (Character.isUpperCase(c))
{
chars[i] = Character.toLowerCase(c);
}
else if (Character.isLowerCase(c))
{
chars[i] = Character.toUpperCase(c);
}
}
return new String(chars);
}
Note that this doesn't do the locale-specific changing that String.toUpperCase/String.toLowerCase does. It also doesn't handle non-BMP characters.