String類常用方法

2021-09-24 20:57:40 字數 2729 閱讀 8702

返回字串長度

public int length()

返回字串中指定位置的字元

public char charat​(int index)

提取字串

方法說明

public string substring​(int beginindex)

從beginindex位置起,從當前字串中取出剩餘的字元作為乙個新的字串返回

public string substring​(int beginindex, int endindex)

從beginindex位置起,從當前字串中取出到endindex-1位置的字元作為乙個新的字串返回

字串比較

方法說明

public int compareto​(string anotherstring)

該方法是對字串內容按字典順序進行大小比較,通過返回的整數值指明當前字串與引數字串的大小關係。若當前物件比引數大則返回正整數,反之返回負整數,相等返回0

public int comparetoignorecase​(string str)

與compareto方法相似,但忽略大小寫

public boolean equals​(object anobject)

比較當前字串和引數字串,在兩個字串相等的時候返回true,否則返回false

public boolean equalsignorecase(string anotherstring)

與equals方法相似,但忽略大小寫

字串連線

public string concat​(string str)

將引數中的字串str連線到當前字串的後面,效果等價於"+"

字串查詢

方法說明

public int indexof​(int ch)

從當前字串的開頭位置向後查詢,返回字元ch在當前字串中從左邊起首次出現的位置下標,若沒有出現則返回-1

public int indexof​(int ch, int fromindex)

從當前字串中fromindex位置向後查詢,返回字元ch在當前字串中從fromindex位置後面首次出現的位置下標,若沒有出現則返回-1

public int lastindexof​(int ch)

從當前字串的末尾位置向前查詢,返回字元ch在當前字串中從右邊起首次出現的位置下標,若沒有出現則返回-1

public int lastindexof​(int ch, int fromindex)

從當前字串中fromindex位置向前查詢,返回字元ch在當前字串中從fromindex位置前面首次出現的位置下標,若沒有出現則返回-1

public int indexof​(string str)

從當前字串的開頭位置向後查詢,返回字串str在當前字串中從左邊起首次出現的位置下標,若沒有出現則返回-1

public int indexof​(string str, int fromindex)

從當前字串中fromindex位置向後查詢,返回字串str在當前字串中從fromindex位置後面首次出現的位置下標,若沒有出現則返回-1

public int lastindexof​(string str)

從當前字串的末尾位置向前查詢,返回字串str在當前字串中從右邊起首次出現的位置下標,若沒有出現則返回-1

public int lastindexof​(string str, int fromindex)

從當前字串中fromindex位置向錢查詢,返回字串str在當前字串中從fromindex位置前面首次出現的位置下標,若沒有出現則返回-1

大小寫轉換

方法說明

public string tolowercase()

返回將當前字串中所有字元轉換成小寫後的新字串

public string touppercase()

返回將當前字串中所有字元轉換成大寫後的新字串

字元的替換

方法說明

public string replace​(char oldchar, char newchar)

用字元newchar替換當前字串中所有的oldchar字元,返回新的字串

public string replacefirst​(string regex, string replacement)

用字元replacement替換當前字串中遇到的第乙個和字串regex相匹配的子串,返回新的字串

public string replaceall​(string regex, string replacement)

用字元replacement替換當前字串中遇到的所有和字串regex相匹配的子串,返回新的字串

字串拆分

方法說明

public string split​(string regex)

按照字串regex拆分當前字串,返回字串陣列

public string split​(string regex, int limit)

按照字串regex和指定個數limit拆分當前字串(後面不拆了),返回字串陣列

字串格式化

public static string format​(string format, object… args)

例:string str = string.format("%d+%d=%d", num1, num2, num1+num2);

String 類常用方法

字串 就是由多個字元組成的一串陣列 一旦被複製,就不能被改變 public class stringdemo string s2 new string bys system.out.println s2 s2 system.out.println s2.length s2.length 5 syst...

String類常用方法

方法名稱 型別 方法描述 public string char value 構造 將字元陣列變為string類物件 public string char value,int offset int count 構造 將部分字元陣列變為string類物件 public char charat int i...

String類常用方法

string 不可變長的字串行 在做字串拼接的時候會直接在堆中建立乙個新的字串物件,並使用這個字串物件儲存新的值,指標直接指向新的字串物件的位址。stringbuilder 可變長的字串行,執行緒不安全,效率較高 stringbuffer 可變長的字串行,執行緒安全,效率較低 string byte...