enter image description here I am trying to convert lower case to upper case and uppercase to lower case.I have attached a image please refer it and try to help.
public class Java {
public static void main(String[] args) {
String str = "Hey How Are you";
for (int i = 0; i < str.length(); i ) {
char ch = str.charAt(i);
System.out.println(ch);
if (ch.equals(ch.toUpperCase())) {
String newChar = ch.toLowerCase();
System.out.print(newChar);
} else if (ch.equals(ch.toLowerCase())) {
String hey = ch.toUpperCase();
System.out.println(hey);
}
}
}
}
CodePudding user response:
To check if a character is uppercase or lowercase you use the Wrapper class Character.isLowerCase()
public static void main(String[] args) {
String str = "Hey How Are you";
String newString = "";
for (int i = 0; i < str.length(); i ) {
char ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
ch = (char) (((int)ch) 32);
} else if (Character.isLowerCase(ch)) {
ch = (char) (((int)ch) - 32);
}
newString = ch;
}
System.out.println(newString);
}
CodePudding user response:
If it is ASCII, you can do it like this by flipping the bit that differentiates upper and lower case letters.
String s = "This Is A Test.";
String ss = "";
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
c ^= 0x20;
}
ss = c;
}
System.out.println(ss);
prints
tHIS iS a tEST.
Here is how it works.
The difference between upper and lower case letters in ASCII is a single bit in their code. For example.
Z -> 1011010
z -> 1111010
0100000 bit to flip
The difference is in the 6th bit from the right. This is true for all ASCII letters. So you need to flip its value. To do that you can use an exclusive OR operation (^
) which says it can be either 1 or 0 both not both. So
1 ^ 1
is 0
and 0 ^ 1
is 1
.
that bit in hex is positioned a 0x20
from the right so you exclusive OR that location to flip only that bit. Exlusive ORing with 0
bits leaves them as they were.
Of course you can do it like this as well and it is certainly easier to understand. It also works for other than ASCII characters. This uses the trinary operator(?:) to decide which way to alter the case.
ss = "";
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
ss = Character.isLowerCase(c) ?
Character.toUpperCase(c) :
Character.toLowerCase(c);
}
}