方法1:利用toLowerCase()将字符串转化为小写,toUpperCase()将字符串转化为大写。
注意:转化过程并不是对原字符串s进行转化,而是需要形成新的字符串存到S中。
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
System.out.println("原字符串:"+s);
String S = s.toUpperCase();
System.out.println("转化为大写字母:"+S);
System.out.println("此时s没有变化:"+s);
System.out.println("大写字母"+S+"转变为小写字母"+S.toLowerCase());
方法2(强制转化)
实际上是先判断是大写字母还是小写字母,然后再进行ascii值的转化,如果是大写字母想要转换为小写字母,则将原字符加上32再强制转换为char型,同理,如果是小写字母转化为大写字母则要将字符减去32,再转化为char型。
补充:大写字母A-Z的ascii值为65-90,小写字母a-z的ascii值为97-122。
public class Main {
public static void main(String[] args) {
char c = 'a';
char c2 = 0;
if('a'<= c && c <= 'z'){
c2 = lowerToSupper(c);
System.out.println("小写字符为" + c + " 大写字符为"+ c2);
}
if('A' <= c2 && c2 <= 'Z'){
char c3 = upperToLower(c2);
System.out.println("大写字符为" + c2 + " 小写字符为"+ c3);
}
}
public static char upperToLower(char c){
return (char)(c + 32);
}
public static char lowerToSupper(char c){
return (char)(c - 32);
}
}
需要注意的是在用ascii码加的时候需要加32而不是26。