1.

Write a program in Java to Toggle the case of every character of a string. For instance, if the input string is “ApPLe”, the output should be “aPplE”.

Answer»

We know that in Java, we cannot make changes to the same string as it is immutable. So, we have to return a new String. The lowercase ASCII characters differ from the uppercase ASCII characters by 32. This means ‘a’ - 32 = ‘A’. So, we will use this concept to Toggle the String cases.

Java Code to Toggle Cases

import java.util.*;
class Main {
public static void main(String args[]) {
// Your code goes here
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();
StringBuilder res = new StringBuilder("");

for(int i=0;i<str.length();i++) {
char ch = str.charAt(i); //current character
if(ch >='A' && ch <= 'Z') {
res.append((char)(ch + 32));
} else if(ch >='a' && ch<='z'){
res.append((char)(ch - 32));
} else {
res.append(ch);
}
}

String ans = res.toString();
System.out.println("The string after toggling becomes: " + ans);
}
}

Sample Output:

Input: Ab#$Cd
Output: aB#$cD


  • Corner Cases, You Might Miss: The String can contain other characters apart from the alphabet. So, in that case, we do not have to change those characters that are not alphabets, while we have to toggle the alphabets. Hence, in the code, after the if condition, we have an else-if condition and not the else condition; otherwise it would have subtracted 32 from every character that is not an uppercase alphabet. In the else condition, we have added the character as it is. This is also seen in the output shown above.


  • Time Complexity: Since we have used a StringBuilder in place of a String, the time complexity of inserting a character in a StringBuilder is O(1). Since we are inserting N characters, the time complexity is O(N). {Here N is the length of the input string}


  • Auxiliary Space: O(1) as we have not used any extra space to solve the problem. The string ans and StringBuilder res are the output spaces and not the auxiliary space.




Discussion

No Comment Found