Java StringBuffer和StringBuilder類

來源:互聯網
上載者:User

標籤:方法   列表   類的方法   stat   string   int end   表示   速度   min   

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()
返回此序列中資料的字串表示形式。

Java StringBuffer和StringBuilder類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.