public class CharToAscii {
public static void main(String[] args) {
CharToAscii.AscToString();
CharToAscii.StringToAsc();
char a = '0';
int b = 22307;
//char類型參與四則運算的時候是轉化成asciii碼的, 字符‘0’的ascii碼為48,要轉換成int型,只需要(‘0’-48)即可
System.out.println(a-48);
System.out.println((int)a); //將char型強行轉制為int型得到的是Ascii碼
System.out.println((char)b);//將int型強行轉制為char型得到的是字符
}
public static void AscToString() { //ASCII轉換為字符串
String s = "22307 35806 24555 20048";
String[] chars = s.split(" ");
for (int i = 0; i < chars.length; i++){
System.out.println(chars[i] + " " + (char)Integer.parseInt(chars[i]));
}
}
public static void StringToAsc() { //字符串轉換為ASCII碼
String s = "新年快樂!";
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++){
System.out.println(" " + chars[i] + " " + (int)chars[i] );
}
}
}