InterviewSolution
Saved Bookmarks
| 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#$CdOutput: aB#$cD
|
|