How can I invert the case of a String in Java?

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.

so "AbCdE123" becomes "aBcDe123"

I guess there must be a way to iterate through the String and flip each character, or perhaps some regular expression that could do it.


Solution 1:

Apache Commons StringUtils has a swapCase method.

Solution 2:

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.