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
相关用法
- C# StringBuilder.ToString用法及代码示例
- C# StringBuilder.CopyTo()用法及代码示例
- C# StringBuilder.EnsureCapacity()用法及代码示例
- C# StringBuilder.CopyTo用法及代码示例
- C# StringBuilder.Chars[]用法及代码示例
- C# String.ToUpperInvariant用法及代码示例
- C# String ToString()用法及代码示例
- C# String Contains()用法及代码示例
- C# String ToCharArray()用法及代码示例
- C# String IndexOf()用法及代码示例
- C# String TrimEnd()用法及代码示例
- C# String Concat()用法及代码示例
- C# String IsNormalized()用法及代码示例
- C# String.ToLowerInvariant用法及代码示例
- C# String.IsNullOrEmpty()用法及代码示例
- C# String GetTypeCode()用法及代码示例
- C# String Equals()用法及代码示例
- C# String CopyTo()用法及代码示例
- C# String Split()用法及代码示例
- C# String.ToCharArray()用法及代码示例
注:本文由纯净天空筛选整理自AmitDiwan大神的英文原创作品 StringBuilder.ToString() Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。