Define a class to accept a string, and print the characters with the uppercase and lowercase reversed, but all the other characters should remain the same as before.
EXAMPLE:
INPUT: WelCoMe_2022
OUTPUT: wELcOmE_2022
Video Link:
Solution:
import java.util.Scanner;
public class Year2022Q1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = sc.nextLine();
String newStr="";
int len=str.length();
// Method 1
for(int i=0;i<len;i++)
{
char ch=str.charAt(i);
if(Character.isUpperCase(ch))
newStr = newStr + Character.toLowerCase(ch);
else if(Character.isLowerCase(ch))
newStr += Character.toUpperCase(ch);
else
newStr+=ch;
}
// Method 2
for(int i=0;i<len;i++)
{
char ch=str.charAt(i);
if(ch>='A' && ch<='Z')
newStr = newStr + Character.toLowerCase(ch);
else if(ch>='a' && ch<='z')
newStr += Character.toUpperCase(ch);
else
newStr+=ch;
}
System.out.println(newStr);
}
}
Output:
No comments:
Post a Comment