C#中String和StringBuilder的简介与区别

2020-01-05 09:51:43王振洲


static void Main(string[] args)
    {
      StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
      MyStringBuilder.Insert(6, "插入");
      Console.WriteLine(MyStringBuilder); //输出为: Hello 插入World!
      Console.Read();
}

4:StringBuilder.Remove(p,n)。在当前StringBuilder对象中移除指定的字符,就是说从p位置开始删除n个字符


static void Main(string[] args)
    {
      StringBuilder Mysb = new StringBuilder("Hello World!");
      Mysb.Remove(2,2);
      Console.WriteLine(MyStringBuilder); //输出为:heo world
      Console.Read();
}

5:StringBuilder.Replace(a,b)。就是用b替换a指定字符串,a和b都是字符或字符串。  


static void Main(string[] args)
    {
      string a = "aaa.Baidu.com";
      string b = a.Replace('a','w');
      Console.WriteLine(b);   // 输出:www.Baidu.com
}

实际上,当我们创建 StringBuilder 对象的时候,.NET 运行库会为当前的对象在内存中分配一块缓存区域,用以对字符串操作的预留空间。在使用 StringBuilder 类的时候,最好将容量设置为字符串可能的最大长度,确保 StringBuilder 不需要重复分配内存。如果字符的容量超过设置的最大容量,.NET 运行库将自动分配内存并翻倍。

对于我们 .NET 程序员而言,StringBuilder 与 String 的不同之处就在于,StringBuilder 可以显示的设置分配内存的大小,而 String 只能根据你初始化时的字符串的大小由系统分配足够的内存。