Monday 26 November 2012

c sharp programming

The System.Text.StringBuilder Type


Given that the string type can be inefficient when used with reckless abandon, the .NET base class
libraries provide the System.Text namespace. Within this (relatively small) namespace lives a class
named StringBuilder. Like the System.String class, the StringBuilder defines methods that allow you
to replace or format segments, for example. When you wish to use this type in your C# code files, your
first step is to make sure the following namespace is imported into your code file:

// StringBuilder lives here!
using System.Text;

What is unique about the StringBuilder is that when you call members of this type, you are directly
modifying the object’s internal character data (making it more efficient), not obtaining a copy of the data
in a modified format. When you create an instance of the StringBuilder, you can supply the object’s
initial startup values via one of many constructors. If you are new to the topic of constructors, simply
understand that constructors allow you to create an object with an initial state when you apply the new
keyword. Consider the following usage of StringBuilder:

static void FunWithStringBuilder()
{
  Console.WriteLine("=> Using the StringBuilder:");
  StringBuilder sb = new StringBuilder("**** Fantastic Games ****");
  sb.Append("\n");
  sb.AppendLine("Half Life");
  sb.AppendLine("Beyond Good and Evil");
  sb.AppendLine("Deus Ex 2");
  sb.AppendLine("System Shock");
  Console.WriteLine(sb.ToString());

  sb.Replace("2", "Invisible War");
  Console.WriteLine(sb.ToString());
  Console.WriteLine("sb has {0} chars.", sb.Length);
  Console.WriteLine();
}

Here we have constructed a StringBuilder set to the initial value "**** Fantastic Games ****". As
you can see, we are appending to the internal buffer and are able to replace or remove characters at will.
By default, a StringBuilder is only able to initially hold a string of 16 characters or fewer (but will expand
automatically if necessary); however, this default starting value can be changed via an additional
constructor argument.

No comments:

Post a Comment