W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
String類包含許多可用于創(chuàng)建String對(duì)象的構(gòu)造函數(shù)。
默認(rèn)構(gòu)造函數(shù)創(chuàng)建一個(gè)以空字符串作為其內(nèi)容的String對(duì)象。
例如,以下語句創(chuàng)建一個(gè)空的String對(duì)象,并將其引用分配給emptyStr變量:
String emptyStr = new String();
String類包含一個(gè)構(gòu)造函數(shù),它接受另一個(gè)String對(duì)象作為參數(shù)。
String str1 = new String(); String str2 = new String(str1); // Passing a String as an argument
現(xiàn)在str1代表與str2相同的字符序列。在這一點(diǎn)上,str1和str2都代表一個(gè)空字符串。我們也可以傳遞一個(gè)字符串字面量到這個(gè)構(gòu)造函數(shù)。
String str3 = new String(""); String str4 = new String("Have fun!");
在執(zhí)行這兩個(gè)語句之后,str3將引用一個(gè)String對(duì)象,它有一個(gè)空字符串作為其內(nèi)容,而str4將引用一個(gè)String對(duì)象,它有“Have fun!作為其內(nèi)容。
String類包含一個(gè)length()方法,該方法返回String對(duì)象中的字符數(shù)。
方法length()的返回類型是int??兆址拈L(zhǎng)度為零。
public class Main { public static void main(String[] args) { String str1 = new String(); String str2 = new String("Hello"); // 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); } }
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: