Using the StringBuilder Class - CSharp Language Basics

CSharp examples for Language Basics:StringBuilder

Description

Using the StringBuilder Class

Demo Code

using System;/*from w ww.j a  v  a 2s.  c  o m*/
using System.Text;     //For StringBuilder
class BuildName
{
   public static void Main()
   {
      StringBuilder name = new StringBuilder();
      string buffer;
      int marker = 0;
      Console.Write("\nEnter your first name: ");
      buffer = Console.ReadLine();
      if ( buffer != null )
      {
         name.Append(buffer);
         marker = name.Length;
      }
      Console.Write("\nEnter your last name: ");
      buffer = Console.ReadLine();
      if ( buffer != null )
      {
         name.Append(" ");
         name.Append(buffer);
      }
      Console.Write("\nEnter your middle name: ");
      buffer = Console.ReadLine();
      if ( buffer != null )
      {
         name.Insert(marker+1, buffer);
         name.Insert(marker+buffer.Length+1, " ");
      }
      Console.WriteLine("\n\nFull name: {0}", name);
      // Some stats....
      Console.WriteLine("\n\nInfo about StringBuilder string:");
      Console.WriteLine("value: {0}", name);
      Console.WriteLine("Capacity: {0}", name.Capacity);
      Console.WriteLine("Maximum Capacity: {0}", name.MaxCapacity);
      Console.WriteLine("Length: {0}", name.Length);
   }
}

Result


Related Tutorials