最新消息: 新版网站上线了!!!

Java中char[] 和 String 类型占用字节大小问题

×÷ÕߣºÍþÍþß÷ Ô­ÎÄÁ´½Ó£ºhttps://blog.csdn.net/smile_Running/article/details/87211916

ÔÚ C ÓïÑÔÖÐ

1¡¢char a[10] = {"China"} ÖУ¬Õâ¸ö a Õ¼ÓöàÉÙ×Ö½Ú£¿

´ð£ºÕ¼Óà 10 ¸ö×Ö½Ú¡£

½âÎö£ºÉÏÃæ´úÂë¶Ô a ×öÁ˸³ÖµµÄ²Ù×÷£¬

a[0]='C' £¬a[1]='h' £¬a[2]='i' £¬a[3]='n' £¬a[4]='a' £¬a[5]='\0'£¬a[6]='\0'£¬a[7]='\0'£¬a[8]='\0'£¬a[9]='\0'

ËùÒÔ£¬ËüÕ¼ÓõÄÊÇ 10 ¸ö×Ö½Ú¡£

2¡¢Èç¹ûµ¥Ö¸ ¡±China¡° ?

´ð£º¹² 6 ¸ö×Ö½Ú¡£China Õ¼ 5 ¸ö×Ö½Ú£¬×îºóÒÔ '\0' ½áÊø£¬Õ¼ 1 ¸ö×Ö½Ú¡£

ÔÚ Java ÓïÑÔÖÐ

1¡¢String s = "China"; Õ¼¶àÉÙ×Ö½Ú£¿

´ð£ºÕ¼ 5 ¸ö×Ö½Ú¡£

System.out.println(Charset.defaultCharset());//»ñÈ¡ideĬÈϱàÂëÀàÐÍ
String s = new String("China".getBytes());
byte[] b = s.getBytes();
System.out.println("" + b.length);

 ÒÔÉÏ´úÂ룬¿ÉÒÔÊä³ö "China" ËùÕ¼µÄ×Ö½Ú³¤¶ÈΪ 5

2¡¢String s = "Öйú"; Õ¼¶àÉÙ×Ö½Ú£¿

´ð£ºÈç¹ûÊÇ ºº×Ö µÄÇé¿öÐèÒª¿¼ÂDZàÂë¡£

£¨1£©GBK ±àÂ루ideĬÈÏ£©Ê±£¬Ã¿Ò»¸öºº×ÖÕ¼Óà 2 ¸ö×Ö½Ú£¬ÄÇôÖйúÕ¼ 4 ¸ö×Ö½Ú¡£

£¨2£©UTF-8 ±àÂëʱ£¬Ã¿Ò»¸öºº×ÖÕ¼Óà 3 ¸ö×Ö½Ú£¬ÄÇôÖйúÕ¼Óà 6 ¸ö×Ö½Ú¡£

3¡¢×ªÂëÎÊÌ⣬GBK ת UTF-8 ʱ£¬×Ö½ÚÕ¼Óûá±ä´óÂ𣿷´¹ýÀ´ÄØ£¿

//»ñÈ¡µÄÊÇ UTF-8±àÂë
System.out.println(Charset.defaultCharset());
String s;
try {
  s = new String("Öйú".getBytes(),"GBK");
  byte[] b = s.getBytes();
  System.out.println("" + b.length);
 } catch (UnsupportedEncodingException e) {
  e.printStackTrace();
}

ÈçÉÏ´úÂëÊÇ£ºUTF-8 ת GBK ±àÂë¸ñʽ£¬s ³¤¶È´Ó 6 ×Ö½Ú±äΪ 9 ×Ö½Ú¡£

s ÄÚÈݱ仯£ºÖйú ¡ª> 中国

ÒòΪµ±Ç°±àÂëÊÇ UTF-8£¬×ªÂëÖ®ºó±ä³ÉÁË 3 ¸öÎÄ×Ö£¬Õ¼Óà 9 ¸ö×Ö½Ú¡£È»¶ø£¬·´¹ýÀ´µÄÇé¿öÊÇÕâÑùµÄ£º

Öйú (gbk) ¡ª> ?§Û? (utf-8)

s ³¤¶È´Ó 4×Ö½Ú ±ä³ÉÁË 4×Ö½Ú£¬ËäÈ»³¤¶Èû·¢Éú¸Ä±ä£¬µ«ÊÇÎÄ×ÖÒѾ­¸Ä±ä¡£ÕâÀïµÄ £¿ Õ¼Óà 1 ¸ö×Ö½Ú¡£

ÒÔÉϾÍÊDZ¾ÎĵÄÈ«²¿ÄÚÈÝ£¬Ï£Íû¶Ô´ó¼ÒµÄѧϰÓÐËù°ïÖú£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö½Å±¾Ö®¼Ò¡£

转载请注明:谷谷点程序 » Java中char[] 和 String 类型占用字节大小问题