测试utf-8 汉字和字符等一般占多少个字节

如题所述

byte[] b = str.getBytes(unicode); // 从字符串中获得字节System.out.println(unicode:+b.length); //unicode 占 4个字节!!b=str.getBytes(utf-8);System.out.println(utf-8:+b.length); //utf-8汉字英文和中文字符一般占3个字节!!数字和字符一般占1个字节,str = new String(b);System.out.println(str.getBytes(unicode).length);} catch (Exception e) {e.printStackTrace();}}}经过上述的测试,得出下列结果:utf-8汉字英文和中文字符一般占3个字节!!数字和英文字符一般占1个字节,
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-03-27
s.getbytes("unicode");//指定使用unicode编码
s.getbytes();//没指定,则使用utf-8来编码
不同编码,其储存的方式不同,所以值不同
unicode全部2字节,unicode字符串是以两个0x00字节结尾.