-
length() 字符串長度
char[] chars = {'a','b','c'}; String s = new String(chars); int len = s.length();
-
charAt() 截取一個字符
String s; char ch; s = "abc"; ch = s.charAt(1); //返回'b'
-
getChars() 截取多個字符
void getChars(int sourceStart, int sourceEnd, char target[],int targetStart) //sourceStart指定了子串開始字符的下標,sourceEnd指定了子串結束后的下一個字符的下標。因此, 子串包含從sourceStart到sourceEnd-1的字符。接收字符的數組由target指定,target中開始復制子串的下標值是targetStart。
getBytes() 替代getChars()的一種方法是將字符存在字節數組中
toCharArray()
equals()和equalsIgnoreCase() 比較兩個字符串(前者不區分大小寫,后者區分大小寫)。
-
regionMatches() 用于比較一個字符串中特定區域與另一特定區域,它有一個重載的形式允許在比較中忽略大小寫
boolean regionMatches(int startIndex,String str2,int str2StartIndex,int numChars) boolean regionMatches(boolean ignoreCase,int startIndex,String str2,int str2StartIndex,int numChars)
startsWith()和endsWith() 前者決定是否以特定的字符串開始,后者決定是否以特定的字符串結束
-
equals和== 前者是比較字符串對象中的字符,后者是比較兩個對象是否引用同一實例
String s1="Hello"; String s2=new String(s1); s1.eauals(s2); //true s1==s2;//false
-
compareTo()和compareToIgnoreCase() 從字符串的第一位開始比較,如果遇到不同的字符,則馬上返回這兩個字符的ascii值差值..返回值是int類型。前者不忽略大小寫,后者忽略大小寫,其他一樣。
String s = "abcdefg"; System.out.println(s.compareTo("fabcd")); //輸出的結果是-5.因為a的ascii碼值-f的ascii碼值=-5.
indexOf()和lastIndexOf() 前者用來查找字符或者子串第一次辦出現的下標,后者用來查找字符或者子串最后一次出現的地方
-
subString() 用來提取子字符串。它有兩種參數形式
String.substring(int startIndex) String.substring(int startIndex, int endIndex) //前者表示子串是從父串的第startIndex個下標開始取,一直到父串的最后一個下標。 //后者是表示從父串的第StartInde個下標開始取,一直到父串的第endIndex - 1個下標。
concat() 連接兩個字符串,和"+"的作用相同
-
replace() 替換,它有兩種參數形式
//用一個字符在調用字符串中所有出現某個字符的地方進行替換 String.replace(char original, char replacement) String s = "Hello".replace('l', 'w'); //用一個字符序列替換另一個字符序列 String.replace(CharSquence original, CharSquence replacement)
trim() 去掉起始和結尾的空格
valueOf() 轉換為字符串
toLowerCase() 轉換為小寫
toUpperCase() 轉換為大寫
StringBuffer構造函數
//StringBuffer定義了三個構造函數
StringBuffer();
StringBuffer(int size);
StringBuffer(String str);
StringBuffer(CharSequence cahrs);
(1) length()和capacity() 一個StringBuffer的當前長度可通過length()方法得到,而整個可分配空間通過capacity()方法得到。
(2) ensureCapacity() 設置緩存區的大小
void ensureCapacity(int capacity);
(3)setLength() 設置緩存區的長度
void setLength(int length);
(4)charAt()和setCharAt()
char charAt(int where);
void setCharAt(int where, char ch)
(5)getchars()
void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
(6)append() 可把任意類型的數據字符串表示連接到調用的StringBuffer對象的末尾。
int a = 42;
StringBuffer sb = new StringBuffer(40);
String s = sb.append("a=").apppend(a).append("!").toString();
(7)insert() 插入字符串
insert(int index, String str);
insert(int index, char ch);
insert(int index, Object obj);
//index指定將字符串插入到StringBuffer對象中的位置的下標
(8)reverse() 顛倒StringBuffer對象中的字符
(9)delete()和deleteCharAt() 刪除字符
delete(int startIndex, int EndIndex);
deleteCharAt(int loc);
(10)replace() 替換
replace(int startIndex, int endIndex, String str);
(11)subString 截取字符串
StringBuffer和StringBuilder的區別:
前者有加鎖,不容易發生意外狀況(比如在多線程操作的時候)。后者不加鎖,可能會發生意外狀況(比如在多線程操作的時候)