stringbuilder c#

Tuesday, 28 January 2014

stringbuilder c#

StringBuilder is a dynamic object that allows you to expand the number of characters in the string that it encapsulates. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Example with StringBuilder methods

Set the Capacity and Length of stringbuilder 

StringBuilder sb = new StringBuilder("Hello World!", 25);

StringBuilder.Append-Appends information to the end of the current StringBuilder


StringBuilder sb = new StringBuilder("Hello World!");
sb.Append("How are you.");
Console.WriteLine(sb);


StringBuilder.AppendFormat-Replaces a format specifier passed in a string with formatted text


int MyInt = 25;
StringBuilder sb= new StringBuilder("Your total is ");
sb.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(sb);

StringBuilder.Insert-Inserts a string or object into the specified index of the current StringBuilder


StringBuilder sb = new StringBuilder("Hello World!");
sb.Insert(6,"Beautiful ");
Console.WriteLine(sb);

StringBuilder.Remove-Removes a specified number of characters from the current StringBuilder


StringBuilder sb = new StringBuilder("Hello World!");
sb.Remove(5,7);
Console.WriteLine(sb);

StringBuilder.Replace-Replaces a specified character at a specified index


StringBuilder sb = new StringBuilder("Hello World!");
sb.Replace('!', '?');
Console.WriteLine(sb);

Converting a StringBuilder Object to a String

You must convert the StringBuilder object to a String object before you can pass the string represented by the StringBuilder object to a method that has a String parameter or display it in the user interface. You do this conversion by calling the StringBuilder.ToString method.

StringBuilder.ToString() method to display the string.

StringBuilder sb = new StringBuilder("Hello World!");
string str=sb.ToString();
Console.WriteLine(str);

No comments:

Post a Comment