进阶day09-字节数组和字符串的相互转换

This commit is contained in:
2026-03-21 10:55:10 +08:00
parent e1aab3d8e7
commit 54ea3ca515

View File

@@ -0,0 +1,40 @@
package com.inmind.io01;
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 Demo4 {
public static void main(String[] args) {
String str = "abc";
//字符串--->字节数组
byte[] bytes = str.getBytes();
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));
String str1 = "中国";
byte[] bytes1 = str1.getBytes();
System.out.println(bytes1.length);
System.out.println(Arrays.toString(bytes1));
//字节数组--->字符串
String s1 = new String(bytes);
System.out.println(s1);
String s2 = new String(bytes1);
System.out.println(s2);
String s3 = new String(bytes1, 3, 3);
System.out.println(s3);
}
}