C# string類和stringBuilder類的區別

來源:互聯網
上載者:User

  首先兩個類的工作原理不同:string類是一種傳統的修改字串的方式,當把一個字串添加到另一個字串時,系統先是把兩個字串寫入記憶體,接著刪除原來的string對象,然後建立一個string對象,並讀取記憶體中的資料付給該對象。

  而System.Text名字空間下的StringBuilder類就不一樣了,StringBuilder 類提供的Append方法能夠在已有對象的原地進行字串的修改。這樣就會比string的方式省了不少時間(當在一個迴圈中將一個字串串連在一起的時候,使用StringBuilder類可以提升效能)

 

一下摘抄StringBuilder類的說明:

①設定容量和長度

StringBuilder MyStringBuilder = new StringBuilder("Hello World");

 

StringBuilder 對象是動態對象,允許擴充它所封裝的字串中字元的數量,但是可以為它的最大可容字元數指定一個值,即該對象的容量,當修改StringBuilder達到最大容量,它將自動分配新的空間且容量翻倍。

StringBuilder MyStringBuilder = new StringBuilder("Hello,World!",25);

 

也可以用MyStringBuilder.Capatity = 25 ,即Capacity屬性來設定對象的最大長度

②StringBuilder方法的使用

Append 將字串追加到當前StringBuilder的結尾

 

StringBuilder sb = new StringBuilder("Hello,World!");

sb.Append("What a beautiful day.");

Console.WriteLine(sb);

 

輸出:Hello,World!What a beautiful day.

 

AppendFormat 用帶格式文本替換字串中傳遞的格式說明符。

int MyInt = 25;

StringBuilder sb = new StringBuilder("Your total is");

sb.AppendFormat("{0:C}",MyInt);

Console.WriteLine(sb);

 

輸出:Your total is ¥25.00.

 

 

 

Insert 將字串插入到當前StringBuilder 對象指定的索引處。

例如:將一個單詞插入到StringBuilder的第六個位置

 

StringBuilder sb = new StringBuilder("Hello,World!");            sb.Insert(6,"beautiful");

 

輸出:Hello,beautifulWorld!

 

Remove 從當前StringBuilder 對象中移除指定數量的字元。

從零開始的索引處刪除指定的字元數量

 

StringBuilder sb = new StringBuilder("Hello,World!");            sb.Remove(4,3);

 

輸出:Hellorld!

 

Replace 替換指定索引處的字元。

StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); 
MyStringBuilder.Replace('!', ' '); 
Console.WriteLine(MyStringBuilder);  

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.