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

后端 未结 9 1410
感情败类
感情败类 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 12:56

    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();
    }
    

提交回复
热议问题