題目描述
輸入任意個字符串,將其中的小寫字母變爲大寫,大寫字母變爲小寫,其他字符不用處理;
輸入描述:
任意字符串:abcd12#%XYZ
輸出描述:
輸出字符串:ABCD12#%xyz
示例1:
輸入: abcd12#%XYZ
輸出: ABCD12#%xyz
代碼實現:
/**
大小寫轉換
**/
import java.util.Scanner;
class TestChange
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
System.out.println(changeStr(str1));
}
public static String changeStr(String str){
char[] c = str.toCharArray(); //先將字符串轉換成字符數組
int value = 'a'-'A'; //計算大小寫間差值:32
//循環遍歷字符數組
for(int i = 0; i < c.length; i++){
if('a'<=c[i] && c[i] <='z'){
c[i] = (char)(c[i]-value); //小寫變大寫
}else if('A'<=c[i] && c[i] <='Z'){
c[i] = (char)(c[i]+value); //大寫變小寫
}
}
String laststr = new String(c); //再將字符數組轉換成字符串
return laststr;
}
}
運行結果:
附:
char c = (char)('a'-32);
System.out.println('a');
System.out.println('a'-32);
System.out.println(c);
運行結果: