char和String的关系

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010739551/article/details/82683498

一个例子就能明白

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

猜你喜欢

转载自blog.csdn.net/u010739551/article/details/82683498