Java StringBuffer 和 StringBuilder 類

當對字串進行修改的時候,需要使用 StringBuffer 和 StringBuilder 類。

和 String 類不同的是,StringBuffer 和 StringBuilder 類的對象能夠被多次的修改,並且不產生新的未使用對象。

StringBuilder 類在 Java 5 中被提出,它和 StringBuffer 之間的最大不同在於 StringBuilder 的方法不是線程安全的(不能同步訪問)。

由於 StringBuilder 相較於 StringBuffer 有速度優勢,所以多數情況下建議使用 StringBuilder 類。然而在應用程式要求線程安全的情況下,則必須使用 StringBuffer 類。

Test.java 檔代碼:

public class Test{ public static void main(String args[]){ StringBuffer sBuffer = new StringBuffer("IT研修官網:"); sBuffer.append("www"); sBuffer.append(".zaixian"); sBuffer.append(".com"); System.out.println(sBuffer); } }

以上實例編譯運行結果如下:

IT研修官網:www.xuhuhu.com

StringBuffer 方法

以下是 StringBuffer 類支持的主要方法:

序號 方法描述
1 public StringBuffer append(String s)
將指定的字串追加到此字元序列。
2 public StringBuffer reverse()
 將此字元序列用其反轉形式取代。
3 public delete(int start, int end)
移除此序列的子字串中的字元。
4 public insert(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)
返回 String 對象中子字串最後出現的位置。
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()
返回此序列中數據的字串表示形式。