1. 程式人生 > >char和String的關係

char和String的關係

一個例子就能明白

public class AES {

	public static void main(String[] args) throws UnsupportedEncodingException {
		char[] c = new char[]{'好'};//char型別佔兩個位元組,記憶體中使用Unicode編碼儲存,可以儲存中文
		String ss = new String(c);
		System.out.println(ss);//輸出:好
		System.out.println(ss.getBytes().length);//預設編碼UTF-8,佔用3個位元組
		System.out.println(ss.getBytes("gbk").length);//GBK編碼,佔用2個位元組
		System.out.println("-----------------------------------------");
		c = new char[]{'Y'};//char型別佔兩個位元組,記憶體中使用Unicode編碼儲存,可以儲存中文
		ss = new String(c);
		System.out.println(ss);//輸出:Y
		System.out.println(ss.getBytes().length);//預設編碼UTF-8,佔用1個位元組
		System.out.println(ss.getBytes("gbk").length);//GBK編碼,佔用1個位元組
		System.out.println("-----------------------------------------");
		byte[] b = {(byte)229,(byte)165,(byte)189};//好 UTF-8編碼
		String str = new String(b,"UTF-8");
		System.out.println(str);
		System.out.println(str.getBytes().length);
	}

}

結果

 好
 3
 2
-----------------------------------------
Y
1
1
-----------------------------------------

3