創建字串對象
String類包含許多可用於創建String對象的構造函數。默認構造函數創建一個空字元串作為其內容的String對象。
例如,以下語句創建一個空的String對象,並將其引用分配給emptyStr變數:
String emptyStr = new String();
String類包含一個構造函數,它接受另一個String對象作為參數。
String str1 = new String();
String str2 = new String(str1); // Passing a String as an argument
現在str1與str2表示相同的字元序列。 在上面的示例代碼中,str1和str2都代表一個空字元串。也可以傳遞一個字串字面量到這個構造函數。
String str3 = new String("");
String str4 = new String("Learn to use String !");
在執行這兩個語句之後,str3將引用一個String對象,該對象將一個空字元串作為其內容,str4將引用一個String對象,它將“Learn to use String !” 作為其內容。
字串的長度
String類包含一個length()方法,該方法返回String對象中的字元數。length()方法的返回類型是int。空字元串的長度為零。三考以下示例 -
public class Main {
public static void main(String[] args) {
String str1 = new String();
String str2 = new String("Hello,String!");
// Get the length of str1 and str2
int len1 = str1.length();
int len2 = str2.length();
// Display the length of str1 and str2
System.out.println("Length of \"" + str1 + "\" = " + len1);
System.out.println("Length of \"" + str2 + "\" = " + len2);
}
}
上面的代碼生成以下結果。
Length of "" = 0
Length of "Hello,String!" = 13
