String類
聲明字符串
String str=[null]
聲明字符串必須結(jié)果初始化才能使用澡刹,否則編譯器會報(bào)出“變量未被初始化錯誤”
String str1,str2;
str1="we are student"
str1="we are student"
此時str1與str2引用相同的字符串變量她倘,因此具有相同的實(shí)體
字符串查找
indexOf(substr)
String str="we are student";
int position=str.indexOf("a");
lastIndexOf(substr)
str.lastIndexOf(substr)
獲取制定索引位置的字符
str.charAt(int index)
字符串操作
獲取子字符串
str.substring(int beginIndex,int endIndex)
去除空格
str.trim()
字符串替換
str.replace(char oldChar,char newChar)
此方法區(qū)分大小寫
判斷字符串的開始和結(jié)尾
str.startsWith(String prefix)
str.endsWith(String suffix)
判斷當(dāng)前字符串是否以指定的內(nèi)容開始或結(jié)束
判斷字符串是否相等
對字符串對象
進(jìn)行比較不能簡單地使用比較運(yùn)算符“==”送巡,因?yàn)楸容^運(yùn)算符比較的是兩個字符串的地址是否相同 即使兩個字符串的內(nèi)容相同 兩個對象的內(nèi)存地址也是不同的 使用比較運(yùn)算符仍然會返回false
String tom=new String("i am a student");
String jerry=new String("i am a student");
boolean b=(tom==jerry);
b=false;
boolean a=tom.equals(jerry);//equalsIgnoreCase()忽略大小寫比較
a=false;
字母大小寫轉(zhuǎn)換
str.toLowerCase()
str.toUpperCase()
使用以上兩個方法進(jìn)行大小寫轉(zhuǎn)換時山上,數(shù)字或非字符不受影響
字符串分割
str.split(String sign)
sign為分割字符串的分割符套啤,也可以使用正則表達(dá)式
str.split(String sign,int limit)
限定了分割的次數(shù)
字符串生成器
創(chuàng)建成功的字符串對象 其長度是固定的 內(nèi)容不能被改變和編譯 雖然使用+可以達(dá)到附加新字符的目的 但是+會產(chǎn)生一個新的String實(shí)例 會在內(nèi)存中創(chuàng)建新的字符串對象 如果重復(fù)的對字符串進(jìn)行修改 將極大的增大系統(tǒng)開銷 String-Builder
類大大的提高了頻繁增加字符串的效率彤侍。
StringBuilder builder=new StringBuilder("");
builder.append();//追加字符串內(nèi)容
bulider.insert(int offset,int arg);//指定位置插入特定內(nèi)容 offset位置 arg內(nèi)容
bulider.delete(int start,int end);//移除從start處開始一直到end-1處的字符