close
在Java中,如果要將數字轉換成字元或字串,或是反過來將字元字串轉成數字的時候,要充份了解互相轉換的機制,比如說
(char)49會將49以編碼的方式轉換,於是顯示出來的數字是1
如果想要將數字轉換成對應的字元,我通常會先轉換成字串再轉成字元
或許有更好的方法,以下列出各種字元/字串對應成整數的方法
public class demo {
public static void main(String[] args) {
int i = 1;
System.out.println("int to String");//整數轉換成字串
System.out.println(Integer.toString(i));//1 String
System.out.println(""+i);//1 String
System.out.println("int to char");
System.out.println("");
int i2 = 49;
//整數強制型別轉換成字元會當成編碼解讀
System.out.println((char)i2);//1 char
//轉換成字串在拆成字元
System.out.println((""+i2).charAt(0));//4 char
System.out.println((""+i2).charAt(1));//9 char
System.out.println("");
char ch = '1';
System.out.println("char to int");
//強制型別轉換會將字元轉換成編碼數字
System.out.println((int)ch);//49 int
//Character.getNumbericValue()才能取到原來數字
System.out.println(Character.getNumericValue(ch));//1 int
System.out.println("");
String str ="1";
System.out.println("String to int");
//Inter.parseInt()可將字串轉為數字
System.out.println(Integer.parseInt(str));//1 int
//需要讀取字串的編碼數字需要用codePointAt()
System.out.println(str.codePointAt(0));//49 int, ascii of 1
System.out.println("");
}
}
全站熱搜