s-day09-字节数组和字符串的相互转换
This commit is contained in:
@@ -0,0 +1,39 @@
|
|||||||
|
package com.inmind.io_out01;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/*
|
||||||
|
字节数组和字符串的相互转换【回忆】
|
||||||
|
字节数组--->字符串:构造方法
|
||||||
|
String(byte[] bytes) 通过使用平台的默认字符集解码指定的字节数组来构造新的 String 。
|
||||||
|
String(byte[] bytes, int offset, int length) 通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String
|
||||||
|
字符串--->字节数组:成员方法
|
||||||
|
byte[] getBytes() 使用平台的默认字符集将该 String编码为一系列字节,将结果存储到新的字节数组中。
|
||||||
|
|
||||||
|
注意:
|
||||||
|
1.UTF-8:字母和数字都只占1个字节,而一个中文占3个字节
|
||||||
|
2.GBK:字母和数字都只占1个字节,而一个中文占2个字节
|
||||||
|
*/
|
||||||
|
public class Demo03 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String str = "abc";
|
||||||
|
//字符串--->字节数组
|
||||||
|
byte[] bytes = str.getBytes();
|
||||||
|
System.out.println(bytes.length);//3
|
||||||
|
System.out.println(Arrays.toString(bytes));//[97, 98, 99]
|
||||||
|
|
||||||
|
String str1 = "中国";
|
||||||
|
byte[] bytes1 = str1.getBytes();
|
||||||
|
System.out.println(bytes1.length);//6
|
||||||
|
System.out.println(Arrays.toString(bytes1));//[-28, -72, -83, -27, -101, -67]
|
||||||
|
|
||||||
|
//字节数组--->字符串
|
||||||
|
String str2 = new String(bytes);
|
||||||
|
System.out.println(str2);
|
||||||
|
String str3 = new String(bytes1);
|
||||||
|
System.out.println(str3);
|
||||||
|
//String(byte[] bytes, int offset, int length) 通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String
|
||||||
|
String str4 = new String(bytes1,0,3);
|
||||||
|
System.out.println(str4);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user