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 多次浏览

开启你的职业

完成课程即可获得认证

开始
广告
© . All rights reserved.