StringBuilder.ToString() 方法在 C# 中


StringBuilder.ToString() 方法用于将 StringBuilder 的值转换成 String。

语法

语法如下 −

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

以上,参数 begnIndex 是此实例中 substring 的起始位置,而 len 是 substring 的长度。

示例

我们现在来看一个示例 −

 在线演示

using System;
using System.Text;
public class Demo{
   public static void Main(){
      StringBuilder strBuilder = new StringBuilder("Katie");
      Console.WriteLine("String = "+strBuilder.ToString());
      Console.WriteLine("
StringBuilder capacity = "+strBuilder.Capacity);       Console.WriteLine("StringBuilder length = "+strBuilder.Length);       strBuilder.EnsureCapacity(35);       Console.WriteLine("
StringBuilder capacity= "+strBuilder.Capacity);       Console.WriteLine("StringBuilder length = "+strBuilder.Length);       strBuilder.EnsureCapacity(0);       strBuilder.Length = 0;       Console.WriteLine("
StringBuilder 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("
StringBuilder capacity = "+strBuilder.Capacity);       Console.WriteLine("StringBuilder length = "+strBuilder.Length);       strBuilder.EnsureCapacity(35);       Console.WriteLine("
StringBuilder capacity= "+strBuilder.Capacity);       Console.WriteLine("StringBuilder length = "+strBuilder.Length);       strBuilder.EnsureCapacity(0);       strBuilder.Length = 0;       Console.WriteLine("
StringBuilder 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

更新日期: 03-12-2019

2K+ 浏览量

开启您的 职业生涯

通过完成课程来获得认证

开始行动
广告