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# 中的字串。每次都會建立新記憶體。建立後,字串就無法更改,這與 StringBuilde 不同。它不會在記憶體中建立新物件。

設定一個字串 −

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.

更新於: 22-6 月-2020

3K+ 瀏覽量

職業起飛

完成課程獲得認證

立即開始
廣告