5.4.1獲取字符串 substring(index)
String F,result; F="I LOVE you 8.5 year"; result=F.substring(5); System.out.print(result); //E you 8.5 year result=F.substring(5,9); System.out.print(result); //E yo
substring(index)從指定的索引位置開始截取直到該字符串結尾的子字符串
substring(beginindex,endindex)從beginindex的索引位置開始截取直到endindex的子字符串
5.4.2 字符串去除首尾空 str.trim()
返回字符串的副本,即忽略首尾空,str內容不變
String F,result; F=" I LOVE you 8.5 year "; result=F.trim(); System.out.print(result); //I LOVE you 8.5 year System.out.print(F); // I LOVE you 8.5 year
5.4.3字符串替換 str.replace(old,new)全部替換
str.replace返回一個新的字符串,它是通過用 newChar 替換此字符串中出現的所有 oldChar 得到的。
String F,result; F="I LOVE you 8.5 year"; result=F.replace("you", "me"); System.out.print(result); //I LOVE me 8.5 year System.out.print(F); //I LOVE you 8.5 year
5.4.4判斷字串符的開頭和結尾
str.startsWith(String s) 檢測字符串是否以指定的前綴開始。
public boolean startsWith(String prefix, int toffset) 從toffset開始檢測字符串是否以指定的前綴開始。
str.endsWith(String s) 檢測字符串是否以指定的前綴結尾。
String F; F="I LOVE you 8.5 year"; System.out.print(F.startsWith("I")); //true System.out.print(F.startsWith("you")); //false System.out.print(F.endsWith("year")); //true System.out.print(F.startsWith("year",4)); //false
5.4.5判斷字串符是否相等 str.equals() / equalsIgnoreCase()
字符串不能簡單地使用“==”來比較,因爲比較運算符比較的是兩個字符串的地址是否想同
String A=new String("abc"); String B=new String("abc"); System.out.print((A.equals(A))); 區分大小寫 //true String A=new String("abc"); String B=new String("ABC"); System.out.print((A.equalsIgnoreCase(A))); 不區分大小寫 //true
5.4.6按字典排序比較兩個字符串 compareTo
字符串與對象進行比較。
按字典順序比較兩個字符串。
返回值是整型,它是先比較對應字符的大小(ASCII碼順序),如果第一個字符和參數的第一個字符不等,結束比較,返回他們之間的差值,如果第一個字符和參數的第一個字符相等,則以第二個字符和參數的第二個字符做比較,以此類推,直至比較的字符或被比較的字符有一方結束。
String str1 = "Strings"; String str2 = "Strings"; String str3 = "Strings123"; int result = str1.compareTo( str2 ); System.out.println(result); //0 result = str2.compareTo( str3 ); System.out.println(result); //-3 result = str3.compareTo( str1 ); System.out.println(result); //3
5.4.7字母大小轉換 toUpperCase / toLowerCase
String A=new String("abc"); String B=new String("ABC"); System.out.print((A.toUpperCase()));//ABC System.out.print((B.toLowerCase()));//abc
5.4.8字符串分割 split()
split() 方法根據匹配給定的正則表達式來拆分字符串。
public boolean startsWith(String prefix, int toffset)
regex -- 正則表達式分隔符。
limit -- 分割的份數。
public boolean startsWith(String prefix)注意: . 、 $、 | 和 * 等轉義字符,必須得加 \\。
注意:多個分隔符,可以用 | 作爲連字符。
String str2 = new String("www.runoob.com"); System.out.println("轉義字符返回值 :" ); for (String retval: str2.split("\\.",2)) { System.out.println(retval); } //轉義字符返回值 : //www //runoob.com