Latest web development tutorials

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");
       sBuffer.append(" String Buffer");
       System.out.println(sBuffer);  
   }
}

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

test String Buffer

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)
返回最後一次出現的指定子字符串在此字符串中的索引。
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()
返回此序列中數據的字符串表示形式。