2007年11月5日

byte 陣列以及 char 陣列,轉成String型態

http://eason982.blogspot.com/2007/11/byte-char-string.html
以ACCII編碼來看,假設我有一byte陣列如下:

byte[] testbyte = new byte[4];
testbyte[0] = 116; //116,ACCII編碼為t
testbyte[1] = 101; //101,ACCII編碼為e
testbyte[2] = 115; //115,ACCII編碼為s
testbyte[3] = 116; //116,ACCII編碼為t


我要如何把testbyte這個陣列改為String型態,而且String即為"test"?
==>

class strTest2
{
public static void main(String[] args)
{
byte[] testbyte = new byte[4];
testbyte[0] = 116;
testbyte[1] = 101;
testbyte[2] = 115;
testbyte[3] = 116;
String str = new String(testbyte);
System.out.println(str);
}
}

----------------------------------------------------------

同樣的,假設我有一char陣列如下:

char[] testchar = new char[4];
testchar[0] = 't';
testchar[1] = 'e';
testchar[2] = 's';
testchar[3] = 't';

我要如何把testchar這個陣列改為String型態,而且String即為"test"?
==>


class strTest
{
public static void main(String[] args)
{
char[] testchar = new char[4];
testchar[0] = 't';
testchar[1] = 'e';
testchar[2] = 's';
testchar[3] = 't';
String str = new String(testchar);
System.out.println(str);
}
}

沒有留言: