Conversion between String and char[], byte[]

One, String and char[]

1. Character array → string

Constructors of the String class: String(char[]) and String(char[], int offset, int length) respectively create string objects with all characters and part of the characters in the character array.

2. String → character array

  • public char[] toCharArray(): A method to store all characters in a string in a character array.
  • public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Provides a method to store the string within the specified index range into the array.
//String --> char[]:调用String的toCharArray()
String str1 = "abc123";

char[] charArray = str1.toCharArray();
for(int i = 0; i < charArray.length; i++){
    
    
	System.out.printf(charArray[i]);
	//输出的结果为a b c 1 2 3
}

//char[] --> String:调用String的构造器
char[] array = new char[]{
    
    'h','e','l','l','o'};
String str2 = new String(arr);
System.out.printf(str2);
//输出结果为hello

Two, String and byte[]

1. Byte array → string (decoding)

  • String(byte[]): Construct a new String by using the platform's default character set to decode the specified byte array.
  • String(byte[], int offset, int length): Use a part of the specified byte array, that is, take length bytes from the beginning of the array offset to construct a string object.

2. String → byte array (encoding)

  • public byte[] getBytes(): Use the platform's default character set to encode this String into a byte sequence, and store the result in a new byte array.
  • public byte[] getBytes(String charsetName): Use the specified character set to encode this String into a byte sequence, and store the result in a new byte array.

Requirements: When decoding, the character set used for decoding must be consistent with the character set used for encoding, otherwise garbled characters will appear.

/* String --> byte[]:调用String的getBytes() */
String str1 = "abc123中国";
//使用默认的字符集进行编码
byte[] bytes = str1.getBytes();
System.out.println(Arrays.toString(bytes));
//输出结果:[97,98,99,49,50,51,-28,-72,-83,-27,-101,-67]

//使用gbk(国标)字符集编码
byte[] gbks = str1.getBytes("bgk");
System.out.println(Arrays.toString(gbks));
//输出结果:[97,98,99,49,50,51,-42,-48,-71]

/* byte[] --> String:调用String的构造器 */
//使用默认的字符集,进行解码
String str2 = new String(bytes);
System.out.println(str2);
//输出:abc123中国

Guess you like

Origin blog.csdn.net/qq_30068165/article/details/115111768