新手容易混亂的String+和StringBuffer,以及Java的方法引數傳遞方式。下面內容由小編為大家介紹JAVA程式設計String和StringBuffer,供大家參考!
Java StringBuffer和StringBuilder類
當對字串進行修改的時候,需要使用StringBuffer和StringBuilder類。
和String類不同的是,StringBuffer和StringBuilder類的物件能夠被多次的修改,並且不產生新的未使用物件。
StringBuilder類在Java 5中被提出,它和StringBuffer之間的最大不同在於StringBuilder的方法不是執行緒安全的(不能同步訪問)。
由於StringBuilder相較於StringBuffer有速度優勢,所以多數情況下建議使用StringBuilder類。然而在應用程式要求執行緒安全的情況下,則必須使用StringBuffer類。
例項
public class Test{ public static void main(String args[]){ StringBuffer sBuffer = new StringBuffer(" test"); nd(" String Buffer"); tln(sBuffer); }}
以上例項編譯執行結果如下:
test String Buffer
StringBuffer 方法
以下是StringBuffer類支援的主要方法:
序號 | 方法描述 |
---|---|
1 | public StringBuffer append(String s)將指定的字串追加到此字元序列。 |
2 | public StringBuffer reverse() 將此字元序列用其反轉形式取代。 |
3 | public (int start, int end)移除此序列的子字串中的字元。 |
4 | public (int offset, int i)將 int 引數的字串表示形式插入此序列中。 |
5 | replace(int start, int end, String str)使用給定 String 中的字元替換此序列的子字串中的字元。 |
下面列表裡的方法和String類的方法類似:
序號 | 方法描述 |
1 | int capacity()返回當前容量。 |
2 | char charAt(int index)返回此序列中指定索引處的 char 值。 |
3 | void ensureCapacity(int minimumCapacity)確保容量至少等於指定的.最小值。 |
4 | void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)將字元從此序列複製到目標字元陣列 dst。 |
5 | int indexOf(String str)返回第一次出現的指定子字串在該字串中的索引。 |
6 | int indexOf(String str, int fromIndex)從指定的索引處開始,返回第一次出現的指定子字串在該字串中的索引。 |
7 | int lastIndexOf(String str)返回最右邊出現的指定子字串在此字串中的索引。 |
8 | int lastIndexOf(String str, int fromIndex)返回最後一次出現的指定子字串在此字串中的索引。 |
9 | int length() 返回長度(字元數)。 |
10 | void setCharAt(int index, char ch)將給定索引處的字元設定為 ch。 |
11 | void setLength(int newLength)設定字元序列的長度。 |
12 | CharSequence subSequence(int start, int end)返回一個新的字元序列,該字元序列是此序列的子序列。 |
13 | String substring(int start)返回一個新的 String,它包含此字元序列當前所包含的字元子序列。 |
14 | String substring(int start, int end)返回一個新的 String,它包含此序列當前所包含的字元子序列。 |
15 | String toString()返回此序列中資料的字串表示形式。 |