C# 中,可變字串和不可變字串有什麼不同?


可變字串

StringBuilder 是 C# 中的可變字串。透過 StringBuilder,你可以擴充套件字串中字元的數量。一旦字串被建立,該字串將無法被更改,但 StringBuilder 卻可以被擴充套件。它不會在記憶體中建立一個新物件。

設定 StringBuilder −

StringBuilder str = new StringBuilder();

讓我們來看一個示例,學習如何在 C# 中使用 StringBuilder −

示例

 線上演示

using System;
using System.Text;

public class Program {
   public static void Main() {
      StringBuilder str = new StringBuilder("Web World!!",30);
      str.Replace("World", "Arena");

      Console.WriteLine(str);
   }
}

輸出

Web Arena!!

不可變字串

不可變字串是 C# 中的字串。每次都會建立一個新記憶體。一旦字串被建立,它將無法被更改,這與 StringBuilder 不同。它不會在記憶體中建立一個新物件。

設定字串 −

String str = “tim”;

下面是一個字串示例,我們在其中比較兩個字串 −

示例

 線上演示

using System;

namespace StringApplication {

   class StringProg {

      static void Main(string[] args) {
         string str1 = "Steve";
         string str2 = "Ben";

         if (String.Compare(str1, str2) == 0) {
            Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
         } else {
            Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
         }
         Console.ReadKey() ;
      }
   }
}

輸出

Steve and Ben are not equal strings.

更新於:2020 年 6 月 22 日

3000 多次瀏覽

開啟你的職業

完成課程即可獲得認證

開始
廣告