请问字符串解码问题

fivefouryuan 2003-08-20 10:42:04
String hello = "Hello world 世界你好";
hello = new String(hello.getBytes(), "GB2312");
System.out.println(hello.length());//输出16

byte[] b=hello.getBytes("gb2312");
System.out.println(b.length);//输出20

hello = new String(hello.getBytes(), "UTF-8");
System.out.println(hello.length());//输出18

byte[] b=hello.getBytes("UTF-8");
System.out.println(b.length);//输出24


请问这个长度是怎么计算出来的,


就是第三个不好理解,字符串的长度空间是怎样计算的
16:每个字符(包括中文)长度为1,gb2312,转换成byte时,英文占一个字节中文占两个
字节,UTF-8时,英文一个字节,中文三个字节,输出24,但是长度为什么是18呢?

谢谢
...全文
23 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wbel 2003-08-21
  • 打赏
  • 举报
回复
import java.io.UnsupportedEncodingException;
public class ziFuChuan{
public static void main(String arg[]){
String hello = "Hello world 世界你好";
try{
hello = new String(hello.getBytes(), "GB2312");
byte[] b=hello.getBytes("gb2312");
System.out.println(b.length);//输出20

hello = new String(hello.getBytes(), "UTF-8");
System.out.println(hello.length());//输出18

byte[] b1=hello.getBytes("UTF-8");
System.out.println(b1.length);//输出28
System.out.println(hello.length());//输出18

}
catch(UnsupportedEncodingException e){}


}
}
fivefouryuan 2003-08-21
  • 打赏
  • 举报
回复
这个是源程序,还是搞不懂怎么得出来的
import java.io.UnsupportedEncodingException;
public class ZiFuChuan{
public static void main(String arg[]){
String hello = "Hello world 世界你好";
try{
//hello = new String(hello.getBytes(), "GB2312");
byte[] b=hello.getBytes("gb2312");
System.out.println(b.length);//输出20

String hello1 = new String(hello.getBytes(), "gb2312");
System.out.println(hello1.length());//输出16
//hello=new String(hello.getBytes(),"UTF-8");//----(1)
byte[] b1=hello.getBytes("UTF-8");
System.out.println(b1.length);//输出24,如果加上(1)输出28
String hello2=new String(hello.getBytes(),"UTF-8");
System.out.println(hello2.length());//输出18

}
catch(UnsupportedEncodingException e){}


}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧