当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# StringBuilder.ToString()用法及代码示例


C# 中的 StringBuilder.ToString() 方法用于将 StringBuilder 的值转换为 String。

用法

语法如下 -

public override string ToString ();
public string ToString (int begnIndex, int len);

上面,参数 begnIndex 是这个实例中子串的起始位置,而 len 是子串的长度。

示例

现在让我们看一个例子 -

using System;
using System.Text;
public class Demo{
   public static void Main(){
      StringBuilder strBuilder = new StringBuilder("Katie");
      Console.WriteLine("String = "+strBuilder.ToString());
      Console.WriteLine("\nStringBuilder capacity = "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
      strBuilder.EnsureCapacity(35);
      Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
      strBuilder.EnsureCapacity(0);
      strBuilder.Length = 0;
      Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
   }
}

输出

这将产生以下输出 -

String = Katie
StringBuilder capacity = 16
StringBuilder length = 5
StringBuilder capacity= 35
StringBuilder length = 5
StringBuilder capacity= 35
StringBuilder length = 0

示例

现在让我们看另一个例子 -

using System;
using System.Text;
public class Demo{
   public static void Main(){
      StringBuilder strBuilder = new StringBuilder("TomHanks");
      Console.WriteLine("StringBuilder = "+strBuilder.ToString());
      Console.WriteLine("String = "+strBuilder.ToString(3, 5));
      Console.WriteLine("\nStringBuilder capacity = "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
      strBuilder.EnsureCapacity(35);
      Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
      strBuilder.EnsureCapacity(0);
      strBuilder.Length = 0;
      Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
   }
}

输出

这将产生以下输出 -

StringBuilder = TomHanks
String = Hanks
StringBuilder capacity = 16
StringBuilder length = 8
StringBuilder capacity= 35
StringBuilder length = 8
StringBuilder capacity= 35
StringBuilder length = 0

相关用法


注:本文由纯净天空筛选整理自AmitDiwan大神的英文原创作品 StringBuilder.ToString() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。