StringBuilder method Illustration - CSharp Language Basics

CSharp examples for Language Basics:StringBuilder

Description

StringBuilder method Illustration

Demo Code

using System;/*from  w  w  w. j  ava 2s. co m*/
using System.Text;
class Program
{
   static void Main(string[] args)
   {
      Console.WriteLine("\nUsing a StringBuilder to concatenate strings:");
      StringBuilder builder = new StringBuilder("012");
      builder.Append("34");
      builder.Append("56");
      Console.WriteLine(builder.ToString()); // result = 0123456.
      Console.WriteLine("\nDefault StringBuilder has capacity for 16 chars:");
      StringBuilder builder2 = new StringBuilder();  // 16 characters.
      Console.WriteLine("Capacity of default StringBuilder: {0}, and contents = {1}", builder2.Capacity, builder2.ToString());
      Console.WriteLine("\nYou can specify an initial capacity for the StringBuilder:");
      StringBuilder builder3 = new StringBuilder(256);
      Console.WriteLine("capacity of 256-char StringBuilder: {0}, and contents = {1}", builder3.Capacity, builder3.ToString());
      Console.WriteLine("\nStringBuilder is especially useful for " + "tasks like concatenating lots of strings:");
      string[] catNames = { "S", "T", "B", "S","B", "P", "E","O", "P", "C", "W" };
      StringBuilder builder4 = new StringBuilder(32000);
      Console.WriteLine("Capacity of huge StringBuilder 32,000: " + "{0}, and contents = {1}", builder4.Capacity, builder4.ToString());
      for (int i = 0; i < catNames.Length; i++)
      {
         builder4.Append(catNames[i]);    // Same list of names as earlier.
      }
      Console.WriteLine("ConCATenated CAT names: {0}", builder4.ToString());
      Console.WriteLine("\nUse a StringBuilder to handle uppercasing " + "an individual char in a string:");
      StringBuilder builder5 = new StringBuilder("jones");
      builder5[0] = char.ToUpper(builder5[0]);
      string fixedString = builder5.ToString();
      Console.WriteLine(fixedString);
   }
}

Result


Related Tutorials