Java program to find string toggle
Toggle means converting small letters into capital letters and vice versa.It can be clearly explained with an example given below
Example: If the given input is 'String' then the output should be 'sTRING'
INPUT: String
OUTPUT: sTRING
Program:
| /*Java program to find string toggle*/ import java.util.*; class toggle { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the string to be toggled: "); String str = sc.nextLine(); char n[] = str.toCharArray(); for(int s = 0; s < n.length; s ++) { if(n[s] >= 'A' && n[s] <= 'Z') { n[s] = (char)((int)n[s] + 32); } if(n[s] >= 'a' && n[s] <= 'z') { n[s] = (char)((int)n[s] - 32); } } System.out.println("The toggled string is :"); for(int s = 0; s < n.length; s ++) System.out.print(n[s]); } } |
Output:
Enter the string to be toggled: CodIng The toggled string is :cODiNG |
First we declare an Scanner class object, then we ask the user to give the sentence or word as input. We take the input using the Scanner class method called "nextLine()", by using this method we get input in the form of a String and then we consider a Character array and we covert the given String into the Character array and this is used because we should consider each and every letter in the word and toggle it so, we take a loop and then we iterate the loop from the first letter of the word to last letter of the word.
Next we have two conditions i.e when the letter is in lower case, we Subtract '32' from the word which makes the letter as Capital letter. This is done by using the ASSICI numbers and when the letter is in upper case we Add '32' to the letter to make it a lower case.
Thus after iteration we come out of the loop. By using an other for loop we print the toggled String as output on the screen.
Next we have two conditions i.e when the letter is in lower case, we Subtract '32' from the word which makes the letter as Capital letter. This is done by using the ASSICI numbers and when the letter is in upper case we Add '32' to the letter to make it a lower case.
Thus after iteration we come out of the loop. By using an other for loop we print the toggled String as output on the screen.
No comments:
Post a Comment