Java String 方法
一.下面是 String 類支持的方法,更多詳細,參看 Java String API 文檔:
二.String類常用方法
1、求字符串長度
public int length()//返回該字符串的長度
2.求字符串某一位置字符
public char charAt(int index)//返回字符串中指定位置的字符;注意字符串中第一個字符索引是0,最后一個是length()-1。
3.提取子串
用String類的substring方法可以提取字符串中的子串,該方法有兩種常用參數:
1)public String substring(int beginIndex)//該方法從beginIndex位置起,從當前字符串中取出剩余的字符作為一個新的字符串返回。
2)public String substring(int beginIndex, int endIndex)//該方法從beginIndex位置起,從當前字符串中取出到endIndex-1位置的字符作為一個新的字符串返回。
以上程序執行結果為:
返回值 :runoob.com 返回值 :runoob
4.字符串比較
1)public int compareTo(String anotherString)//該方法是對字符串內容按字典順序進行大小比較,通過返回的整數值指明當前
字符串與參數字符串的大小關系。若當前對象比參數大則返回正整數,反之返回負整數,相等返回0。
2)public int compareToIgnore(String anotherString)//與compareTo方法相似,但忽略大小寫。
3)public boolean equals(Object anotherObject)//比較當前字符串和參數字符串,在兩個字符串相等的時候返回true,否則返回false。
4)public boolean equalsIgnoreCase(String anotherString)//與equals方法相似,但忽略大小寫。
參數
-
-
o -- 要比較的對象。
-
anotherString -- 要比較的字符串。
-
返回值
返回值是整型,它是先比較對應字符的大小(ASCII碼順序),如果第一個字符和參數的第一個字符不等,結束比較,返回他們之間的差值,如果第一個字符和參數的第一個字符相等,則以第二個字符和參數的第二個字符做比較,以此類推,直至比較的字符或被比較的字符有一方。
-
- 如果參數字符串等於此字符串,則返回值 0;
- 如果此字符串小於字符串參數,則返回一個小於 0 的值;
- 如果此字符串大於字符串參數,則返回一個大於 0 的值。
String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b = str1.compareToIgnoreCase(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d = str1.equalsIgnoreCase(str2);//d=true
5.字符串連接
public String concat(String str)//將參數中的字符串str連接到當前字符串的后面,效果等價於"+"。
1)public int indexOf(int ch/String str)//用於查找當前字符串中字符或子串,返回字符或子串在當前字符串中從左邊起首次出現的位置,若沒有出現則返回-1。
2)public int indexOf(int ch/String str, int fromIndex)//改方法與第一種類似,區別在於該方法從fromIndex位置向后查找。
3)public int lastIndexOf(int ch/String str)//該方法與第一種類似,區別在於該方法從字符串的末尾位置向前查找。
4)public int lastIndexOf(int ch/String str, int fromIndex)//該方法與第二種方法類似,區別於該方法從fromIndex位置向前查找。
String str = "I am a good student";
int a = str.indexOf('a');//a = 2
int b = str.indexOf("good");//b = 7
int c = str.indexOf("w",2);//c = -1
int d = str.lastIndexOf("a");//d = 5
int e = str.lastIndexOf("a",3);//e = 2
7.字符串中字符的大小寫轉換
1)public String toLowerCase()//返回將當前字符串中所有字符轉換成小寫后的新串
2)public String toUpperCase()//返回將當前字符串中所有字符轉換成大寫后的新串


8.字符串中字符的替換
1)public String replace(char oldChar, char newChar)
//用字符newChar替換當前字符串中所有的oldChar字符,並返回一個新的字符串。
2)public String replaceFirst(String regex, String replacement)
//該方法用字符replacement的內容替換當前字符串中遇到的第一個和字符串regex相匹配的子串,應將新的字符串返回。
3)public String replaceAll(String regex, String replacement)
//該方法用字符replacement的內容替換當前字符串中遇到的所有和字符串regex相匹配的子串,應將新的字符串返回。


