public class Test{ public static void main(String[] args){
String s1="中华人民共和国abc123"; byte[] b = new byte[5];
b=s1.getBytes();
for(int i=0;i<b.length;i++){
System.out.println(b[i]);
}
}
}这段代码运行后,结果如下:
-42
-48
-69
-86
-56
-53
-61
-15
-71
-78
-70
-51
-71
-6
97
98
99
49
50
51为什么getBytes()不能得到字符串中各个字符?
String s1="中华人民共和国abc123"; byte[] b = new byte[5];
b=s1.getBytes();
for(int i=0;i<b.length;i++){
System.out.println(b[i]);
}
}
}这段代码运行后,结果如下:
-42
-48
-69
-86
-56
-53
-61
-15
-71
-78
-70
-51
-71
-6
97
98
99
49
50
51为什么getBytes()不能得到字符串中各个字符?
使用 s1.toCharArray()
这个是返回字符数组的,
你那个是返回字节数组,两个是不一样的
比如一个“中”字的字节码假如是6789,存在String里的两个字节分别是67,89,当67以单个字节输出来的话,你也不知道他是什么,你不可能知道他是中字的前半部分,程序也不可能知道。
b = s1.getBytes();
for (int i = 0; i < b.length; i++) {
System.out.println((char)(b[i]));
}
}你会发现abc123输出来了,前面的汉字输出乱码,这就是因为abc123都占一个字节,汉字占两个字节
public static void main(String[] args) {
String s1 = "中华人民共和国abc123";
char [] array=s1.toCharArray();
for(char ch:array){
System.out.println(ch);
}
}
public class Test{
public static void main(String[] args){
String s1="中华人民共和国abc123";
char[] b;
b=s1.toCharArray();
for(int i=0;i<b.length;i++){
System.out.println(b[i]);
}
}
}
改成
System.out.println((char)b[i]);
就OK了否则byte是当成int来输出的
lz你问的是为什么得到的不是字符对吧、
你getbytes得到的是二进制、
一个汉字是两个字节、
一个byte存不了一个汉字
s1.toCharArray()
char是16位、
2个字节、
就可以存一个汉字了、
97
98
99
是abc的数字表示(忘了叫什么码了、、asic好像是)
和内存分配那块、
看看c的数据类型那块、
System.out.println(s1.charAt(j));
}
(char)b[i] ;
char才是字符