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