Invert case of a String in Java
This post will discuss how to invert the case of a string in Java. The solution should convert each upper case character present in the string to lower case and lower case characters to the upper case.
1. Naive method
We know that the String class in Java didn’t provide anything built-in to invert the case of a string. However, we can write our custom routine for this easy task. The idea is to iterate through the string and invert the case of each encountered character. Since the string is immutable, we can convert the string to a character array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Main { public static String invertCase(String str) { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { chars[i] = Character.isUpperCase(chars[i]) ? Character.toLowerCase(chars[i]) : Character.toUpperCase(chars[i]); } return new String(chars); } public static void main(String[] args) { String str = "Invert My CASE"; System.out.println(invertCase(str)); } } |
Output:
iNVERT mY case
2. Using Apache Commons Lang
We can also leverage the Apache Commons Lang library, the swapCase() method present in the StringUtils class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.apache.commons.lang3.StringUtils; class Main { public static String invertCase(String str) { return StringUtils.swapCase(str); } public static void main(String[] args) { String str = "Invert My CASE"; System.out.println(invertCase(str)); } } |
That’s all about inverting the case of a Java String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)