public class StringConstructorDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 将位元組數組或者字元數組轉成字元串可以通過String類的構造函數完成。
*/
stringConstructorChar();
stringConstructorByte();
}
/**
* String(char[ ] value):通過char數組構造字元串對象。
* String(char[] value, int offset, int count) //通過字元數組構造字元子數組
*/
private static void stringConstructorChar() {
char[] arr = {'w','a','p','q','x'};
String s0 = new String(arr,1,3);
String s1 = new String(arr);
System.out.println("s="+s0);//輸出s=apq
System.out.println("s="+s1);//輸出s=wapqx
}
/**
* String(byte[ ] bytes):通過byte數組構造字元串對象。
* String(byte[] bytes, int offset, int length) 通過byte數組構造字元串子數組對象
* String(String original) //構造一個original的副本。即:拷貝一個original。
*/
public static void stringConstructorByte() {
byte[] arr = {97,66,67,68};
String s1 = new String(arr);
String s2 = new String(arr, 0, 2);
System.out.println("s1="+s1);//輸出s1=aBCD
System.out.println("s2="+s2);//輸出s2=aB
String sb_copy = new String(s1);//
System.out.println(sb_copy);//輸出aBCD
}
}
轉載于:https://www.cnblogs.com/200911/p/3870538.html