Java基礎—String構造方法
阿新 • • 發佈:2022-03-11
Java基礎——String構造方法
public String(); | 建立一個空表字符串物件,不包含任何內容 |
---|---|
public String(char[]chs); | 根據字元陣列的內容,來建立字串物件,現已不用 |
public String (byte[]bys); | 根據位元組陣列的內容,來建立字串物件 |
String s="abs"; | 直接賦值的方式建立字串物件,內容為雙引號內的字串資料推薦使用 |
//笨方法
public class StringDemo01 {
public static void main(String[] args) {
//方式一
String s = new String();
System.out.println("s=" + s);
//方式二,陣列元素需要遍歷
char[] s2 = {'a', 'b', 'c'};
System.out.print("s2=");
//呼叫遍歷陣列方法
PrintArr(s2);
System.out.println();
//方式三
byte[] s3 = {5, 5, 5};
System.out.print("s3=");
//呼叫遍歷陣列方法
PrintArr(s3);
System.out.println();
//方式四
String s4 = "555";
System.out.println("s4=" + s4);
}
//定義陣列遍歷方法
public static void PrintArr(char[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.print(arr[i]);
} else {
System.out.print(arr[i] + ",");
}
}
System.out.print("]");
}
public static void PrintArr(byte[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.print(arr[i]);
} else {
System.out.print(arr[i] + ",");
}
}
System.out.print("]");
}
}
//簡潔方法
public class StringDemo02 {
public static void main(String[] args) {
//方式一
String s = new String();
System.out.println("s=" + s);
//方式二,陣列元素需要遍歷
char[] crs = {'a', 'b', 'c'};
String s2 = new String(crs);
System.out.println("s2=" + s2);
//方式三
byte[] byt = {5, 5, 5};
String s3 = new String(crs);
System.out.println("s3=" + s3);
//方式四
String s4 = "555";
System.out.println("s4=" + s4);
}
}