String是比較特殊的資料類型,它不屬於基礎資料型別 (Elementary Data Type),但是可以和使用基礎資料型別 (Elementary Data Type)一樣直接賦值,不使用new關鍵字進行執行個體化。也可以像其他類型一樣使用關鍵字new進行執行個體化。下面的代碼都是合法的: String s1 = "this is a string!"; String s2 = new String("this is another string!");另外String在使用的時候不需要用import語句匯入,還可以使用“+”這樣的運算子。如果想把字串串連起來,可以使用“+”完成。例如:s1+s2。String的一些常用方法如下。為了說明方法,方法中使用的樣本字串為:str=“this is a test!”;
求長度方法定義:public int length() 。方法描述:擷取字串中的字元的個數。例如:str.length()結果:15
擷取字串中的字元方法定義:public char charAt(int index)。方法描述:擷取字串中的第index個字元,從0 開始。例如:str.charAt(3)結果:s注意:是第4 個字元。
取子串有兩種形式。形式一如下:方法定義:public String substring(int beginIndex,int endIndex)。方法描述:擷取從beginIndex 開始到endIndex 結束的子串,包括beginIndex,不包括endIndex。例如:str.substring(1,4)結果:his形式二如下:方法定義:public String substring(int beginIndex)方法描述:擷取從beginIndex 開始到結束的子串例如:str.substring(5)結果:is a test!
定位字元或者字串有4種形式。形式一如下:方法定義:public int indexOf(int ch)方法描述:定位參數所指定的字元。例如:str.indexOf(‘i’)結果:2形式二如下:方法定義:public int indexOf(int ch,int index)方法描述:從index開始定位參數所指定的字元。例如:str.indexOf(‘i’,4)結果:5形式三如下:方法定義:public int indexOf(String str)方法描述:定位參數所指定的字串。例如:str.indexOf("is")結果:2形式4如下:方法定義:public int indexOf(String str,int index)方法描述:從index開始定位str所指定的字串。例如:str.indexOf("is",6)結果:-1表示沒有找到
替換字元和字串有3種形式。形式一如下:方法定義:public String replace(char c1,char c2)方法描述:把字串中的字元c1替換成字元c2例如:str.replace('i','I')結果:thIs Is a test!形式二如下:方法定義:public String replaceAll(String s1,String s2)方法描述:把字串中出現的所有的s1替換成s2例如:replaceAll("is","IS")結果:thIS IS a test!形式三如下。方法定義:public String replaceFirst(String s1,String s2)方法描述:把字串中的第一個s1替換成s2例如:replaceFirst("is","IS")結果:thIS is a test! 上一次:
第十七講 基本輸入輸出 下一次:
第十九講 String用法(下) 李緒成 CSDN Blog:http://blog.csdn.net/javaeeteacher 邀請您為好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5