StringBuilder.ToString() Method in C#


The StringBuilder.ToString() method in C# is used to convert the value of a StringBuilder to a String.

Syntax

The syntax is as follows −

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

Above, the parameter begnIndex is the starting position of the substring in this instance, whereas len is the length of the substring.

Example

Let us now see an example −

 Live Demo

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);
   }
}

Output

This will produce the following output −

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

Example

Let us now see another example −

 Live Demo

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);
   }
}

Output

This will produce the following output −

StringBuilder = TomHanks
String = Hanks
StringBuilder capacity = 16
StringBuilder length = 8
StringBuilder capacity= 35
StringBuilder length = 8
StringBuilder capacity= 35
StringBuilder length = 0
raja
Published on 03-Dec-2019 09:55:31
Advertisements