In this guide, we will learn how to toggle string in Java. Toggle means reversing the case of each character of String (i.e., converting uppercase letters to lowercase and vice versa).
Java Program to Toggle a String
To toggle a given String, you can iterate through each character of String and change its case using toUpperCase()
and toLowerCase()
methods of Character class. Here is an example of how you can do this:
public class ToggleStringCase {
public static void main(String[] args) {
String str = "Hello World!";
//calling user defined method to toggle string
String toggled = toggleCase(str);
System.out.println(toggled);
}
public static String toggleCase(String str) {
StringBuilder toggledStr = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// if a character is in uppercase, change it to lowercase
// and if a character is in lowercase, change it to uppercase
if (Character.isUpperCase(c)) {
toggledStr.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
toggledStr.append(Character.toUpperCase(c));
} else {
toggledStr.append(c);
}
}
return toggledStr.toString();
}
}
Output:
hELLO wORLD!
Explanation:
- Initialization:
- The
str
variable contains the string which we want to toggle - The
toggleCase()
method is called withstr
and its returned value is stored intoggled
.
- The
- toggleCase() Method:
- In this method we traverse through the whole String using for loop.
- The case of every character is checked using
isUpperCase()
andisLowerCase()
methods of Character class. - If a character is in upper case it is changed to lowercase using
toLowerCase()
method and if it is in lowercase, it is changed to uppercase usingtoUpperCase()
.
- Output:
- It prints the string returned by
toggleCase()
method, which is a toggled string.
- It prints the string returned by
Leave a Reply