Once created a string cannot be changed. A StringBuilder can be changed as many times as
necessary. It yields astonishing performance improvements. It eliminates
millions of string copies. And in certain loops it is essential.
Example 1
As an introduction, this program shows how the StringBuilder type
is used to build up a larger buffer of characters. You can call the Append
method on the StringBuilder instance to add more and more data.
using System;
using System.Text;
class Program
{
static void Main()
{
StringBuilder builder = new StringBuilder();
// Append to StringBuilder.
for (int i = 0; i < 10; i++)
{
builder.Append(i).Append(" ");
}
Console.WriteLine(builder);
}
}
Output:
0 1 2 3 4 5 6 7 8 9
Example 2:
Next let's look at some of the essential methods on the
StringBuilder type in the base class library. The methods shown here will allow
you to use it effectively in many programs, appending strings and lines.
using System;
using System.Text;
using System.Diagnostics;
class Program
{
static void Main()
{
// 1.
// Declare a new StringBuilder.
StringBuilder builder = new StringBuilder();
// 2.
builder.Append("The list starts here:");
// 3.
builder.AppendLine();
// 4.
builder.Append("1 cat").AppendLine();
// 5.
// Get a reference to the StringBuilder's buffer content.
string innerString = builder.ToString();
// Display with Debug.
Debug.WriteLine(innerString);
}
}
Output:
The list starts here:
1 cat
No comments:
Post a Comment