C#中string和StringBuilder的區別

來源:互聯網
上載者:User

C#中string和StringBuilder的區別

  String用於表示文本,StringBuilder表示值為可變字元序列的類似字串的對象,之所以說是可變的,是因為通過追加、移除、替換或插入字元建立它以後,還可以對其進行修改。同時,在操作長度比較大的字串的時候,使用StringBuilder會更方便。

  下面舉例說明其不同之處:

  (1)定義方式不同

  string str = “Hello World”;

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

  (2)顯示整個字串的時候顯示方式不同。

  Console.WriteLine("{0}",str);

  Console.WriteLine("{0}",sb.Tostring());

  (3)功能不同

  用string可顯示字串的第n個元素,字串長度、刪除字串首尾空格、複製、大小寫、截取字串

  顯示第n個元素:str[n-1];

  字串長度:str.length;

  刪除字串首尾空格:str.Trim();

  複製:str.Clone().Tostring();

  大小寫:str.Toupper();str.Tolower();

  截取:str.substring(n1,n2);  //n1,n2為截取字串的首尾元素在原字串中的位置

  用StringBuilder主要是用來修改字串,如添加文本以及擷取其最大的文本數量。

  在末端添加文本:sb.Append("***");  //***為所添加的內容

  擷取最大文本數量:sb.MaxCapacity

using System;
using System.Collections.Generic;
using System.Text;

namespace StringTypeCommon
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = " Hello World";
            Console.WriteLine("顯示{0}", str);
            Console.WriteLine("第一個{0}", str[0]);
            Console.WriteLine("第二個{0}", str[1]);
            Console.WriteLine("插入字元{0}",str.Insert(6," C#"));
            Console.WriteLine("字串長度{0}", str.Length);
            Console.WriteLine("刪除字串空格{0}", str.Trim());
            Console.WriteLine("字串複製{0}",str.Clone().ToString());
            Console.WriteLine("小寫字串{0}", str.ToLower());
            Console.WriteLine("大寫字串{0}", str.ToUpper());
            Console.WriteLine("截取部分字串{0}", str.Substring(1, 6));
            
            StringBuilder sb = new StringBuilder("Hello World ");
            Console.WriteLine("顯示{0}", sb.ToString());
            Console.WriteLine("末端追加文本{0}", sb.Append("!!!"));
            Console.WriteLine("指定位置添加文本{0}", sb.Insert(6, "dear "));
            Console.WriteLine("最大文本數量{0}", sb.MaxCapacity);

Console.ReadLine();
        }
    }
}

相關文章

聯繫我們

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