[Java] String 類別的方法

char  charAt(int index)
傳回int所指定索引碼的字元

int  compareTo(String anotherString)
逐字元比較其標準萬國碼(Unicode)
若anotherString比較大則回傳一負數,字串內容完全相同則回傳0,若比較小則回傳一正數

boolean  contains(CharSequence s)
傳回布林值表示字串中是否含有s所指之字串內容

boolean  endsWith(String suffix)
傳回布林值表示字串中是否含指定內容之結尾
suffix(後綴)

void  getChar(int srcBegin,int srcEnd,char[] dst,int dstBegin)
將索引碼srcBegin至srcEnd-1(因索引碼起始為0)的字元複製到dst字元陣列中且以索引碼dstBegin為起始位置

public class test{
public static void main(String[] args) {
String s = "abc 這是測試";
char[] chars = new char[4];
s.getChars(0,3,chars,2);
System.out.println(new String(chars));
}
}

result:
abc 這


int  indexOf(int ch)
傳回 ch字元在字串中第一次出現位置的索引碼,若字串中無此字元則回傳-1

int  lastIndexOf(int ch)
與indexOf類似,只是是從字串尾端往前搜尋ch字元

int  indexOf(int ch,int fromIndex)
indexOf()多重定義法,使用fromIndex指定開始搜尋位置,尋找ch字元

int  lastindexOf(int ch,int fromIndex)
與indexOf類似,只是是從字串尾端往前搜尋ch字元

int  indexOf(String str)
indexOf()多重定義法,尋找str字串

int  indexOf(String str, int fromIndex)
indexOf()多重定義法,從fromIndex指定開始搜尋位置,尋找str字串

int  lastindexOf(String str, int fromIndex)
與indexOf類似,只是是從字串尾端往前搜尋str字串

boolean  isEmpty()
判斷是否為空字串(字串長度為0),是則回傳true,否則回傳false

int  length()
傳回字串長度

String replace(char oldChar,char newChar)
將字串中所有出現的oldChar字元以newChar字元取代

String replace(CharSequence target, CharSequence replacement)
將字串中所有出現的target字串以replacement字串取代

boolean startsWith(String prefix)
boolean startsWith(String prefix, int offset)
檢查目前字串是否以prefix為開頭,offset則是從指定索引位置開始檢查

String substring(int beginIndex)
傳回由begInindex所指定索引位置至結尾的子字串

String substring(int beginIndex,int endIndex)
傳回由beginIndex所指定索引位置至endIndex-1的部分字串

String toLowerCase()
String toUpperCase()

String trim()
去除字串頭、尾端的空白符號,包含空白字元、定位字元等

----------
StringBuffer
append() 方法會在字串尾端添加資料
insert(int offset,string data) 方法會在指定的offset索引碼位置之前插入data資料
delete(int start,int end)方法刪除由start至end-1索引碼的一段字元
deleteCharAt(int index)刪除index索引碼的字元
replace(int start,int end,String str)將start至end-1索引碼間的字元以str取代
reverse()字串頭尾反轉
void setCharAt(int index,char ch)將index指定索引碼字元以ch取代,無回傳

StringBuilder與StringBuffer用途與方法相同但在多執行緒環境下建議使用StringBuffer






















留言

熱門文章