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

后端 未结 9 1411
感情败类
感情败类 2020-11-30 12:16

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.

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 13:04

    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.

提交回复
热议问题