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

后端 未结 9 1337
感情败类
感情败类 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 13:16

    Based on Faraz's approach, I think the character conversion can be as simple as:

    t += Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c);
    
    0 讨论(0)
  • 2020-11-30 13:16

    We can also use a StringBuilder object, as it has character replacing methods. However, it might take some extra space to store the StringBuilder object. So, it will help if space does not matter and keep the solution simple to understand.

    String swapCase(String text) {
        StringBuilder textSB = new StringBuilder(text);
        for(int i = 0; i < text.length(); i++) {
            if(text.charAt(i) > 64 && text.charAt(i) < 91)
                textSB.setCharAt(i, (char)(text.charAt(i) + 32));
            else if(text.charAt(i) > 96 && text.charAt(i) < 123)
                textSB.setCharAt(i, (char)(text.charAt(i) - 32));
        }
        return textSB.toString();
    }
    
    0 讨论(0)
  • 2020-11-30 13:16

    I do realize that the given thread is very old, but there is a better way of solving it:

    class Toggle
    { 
        public static void main()
        { 
            String str = "This is a String";
            String t = "";
            for (int x = 0; x < str.length(); x++)
            {  
                char c = str.charAt(x);
                boolean check = Character.isUpperCase(c);
                if (check == true)
                    t = t + Character.toLowerCase(c);
                else
                    t = t + Character.toUpperCase(c);
            }
            System.out.println (t);
        }
    }
    
    0 讨论(0)
提交回复
热议问题