資源描述:
《String類常用方法》由會員上傳分享,免費在線閱讀,更多相關內容在教育資源-天天文庫。
1、ava中String?類的方法及說明String:字符串類型一、構造函數(shù)?????String(byte?[]?bytes?):通過byte數(shù)組構造字符串對象?。?????String(char[]?value?):通過char數(shù)組構造字符串對象?。?????String(Sting?original?):構造一個original?的副本?。即:拷貝一個original?。?????String(StringBuffer?buffer?):通過StringBuffer數(shù)組構造字符串對象。??例如:??????byt
2、e[]b={'a','b','c','d','e','f','g','h','i','j'};??????char[]c={'0','1','2','3','4','5','6','7','8','9'};??????Stringsb=newString(b);?????????????????//abcdefghij??????Stringsb_sub=newString(b,3,2);?????//de??????Stringsc=newString(c);??????????????????//0123456
3、789??????Stringsc_sub=newString(c,3,2);????//34??????Stringsb_copy=newString(sb);???????//abcdefghij?????????System.out.println("sb:"+sb);??????System.out.println("sb_sub:"+sb_sub);??????System.out.println("sc:"+sc);??????System.out.println("sc_sub:"+sc_sub);?
4、?????System.out.println("sb_copy:"+sb_copy);??????輸出結果?:sb:abcdefghij??????????????????????sb_sub:de???????????????????????sc:0123456789????????????????????????sc_sub:34????????????????????????sb_copy:abcdefghij二、方法:?????說明:①、所有方法均為public。???????????②、書寫格式:[修飾
5、符]<返回類型><方法名([參數(shù)列表])>??????例如:staticintparseInt(Strings)??????表示此方法(parseInt)為類方法(static),返回類型為(int),方法所需要為String類型。1.?char?charAt?(intindex)?:取字符串中的某一個字符?,其中的參數(shù)index指的是字符串中序數(shù)。字符串的序數(shù)從0開始到length()-1。????例如:Strings=newString("abcdefghijklmnopqrstuvwxyz");???????
6、???System.out.println("s.charAt(5):"+s.charAt(5));??????????結果為:s.charAt(5):f2.?intcompareTo(StringanotherString)?:當前String對象與anotherString比較?。相等?關系返回0?;不相等?時,從兩個字符串第0個字符開始比較,返回第一個不相等的字符差?,另一種情況,較長字符串的前面部分恰巧是較短的字符串,返回它們的長度差。3.?intcompareTo(Objecto)?:如果o是String
7、對象,和2的功能一樣;否則拋出ClassCastException?異常。????例如:Strings1=newString("abcdefghijklmn");????????????Strings2=newString("abcdefghij");???????????Strings3=newString("abcdefghijalmn");???????????System.out.println("s1.compareTo(s2):"+s1.compareTo(s2));//返回長度差???????????
8、System.out.println("s1.compareTo(s3):"+s1.compareTo(s3));//返回'k'-'a'的差???????????結果為:s1.compareTo(s2):4???????????????????????s1.compareTo(s3):104.?Stringconcat(Stringstr)?:將該Strin