As I mentioned in the post Char Data Type, that the characters in Java use unicode set and are represented as unsigned 16-bit in memory and use char data type. char data type is converted implicitly into an int data type and can be handled as an integer (add / subtract an integer value). We have already seen this in my earlier post.
Let's make use of these following features of char data type and String class to change alphabets cases (lowercase to uppercase or uppercase to lowercase) -
- char data type is represented as an integer value and its range is 0 to 65,535. char data type values can be manipulated like integers.
- Uppercase alphabets (A~Z) have values from 65 to 90. And lowercase letters (a~z) have values from 97 to 122
- String object can be converted into a character array by String class method toCharArray() and a character array can also be converted back into string by String class's static method valueOf().
- After converting to the character array, 32 is added to all uppercase alphabets and 32 is subtracted from all lowercase alphabets. Result values are int data type and can't be converted to char data type back automatically. Type casting (Explicit Conversion) is needed to convert int to char data type.
import java.util.Scanner;
public class CaseChange {
public static void main(String args[]) {
String s1, s2;
char ch[];
System.out.println("Enter the string:");
Scanner sc = new Scanner(System.in);
s1 = sc.nextLine();
// Convert the string to character array
ch = s1.toCharArray();
s2 = changeCase(ch);
System.out.println();
System.out.println("String Case Changed:");
System.out.println(s2);
}
public static String changeCase(char[] ch) {
// Manipulate all the characters in array
for(int i = 0; i < ch.length; i++) {
if((ch[i] >= 65) && (ch[i] <= 90)) {
// If the character is A~Z
ch[i] = (char)(ch[i] + 32);
}
else if((ch[i] >= 97) && (ch[i] <= 122))
{
// If the character is a~z
ch[i] = (char)(ch[i] - 32);
}
}
// Convert character array back to the string
String str = String.valueOf(ch);
return str;
}
}
Output is:
Enter the string:
Object-Oriented Programming
String Case Changed:
oBJECT-oRIENTED pROGRAMMING
No comments:
Post a Comment