Information Technology Reference
In-Depth Information
For example, the following code declares and initializes a string called s . The first
WriteLine statement calls the ToUpper method on s , which returns a copy of the string that is
in all uppercase. The last line prints out the value of s , showing that it is unchanged.
string s = "Hi there.";
Console.WriteLine("{0}", s.ToUpper()); // Print uppercase copy.
Console.WriteLine("{0}", s); // String is unchanged.
This code produces the following output:
HI THERE.
Hi there.
Using Class StringBuilder
The StringBuilder class produces strings that can be changed.
￿The StringBuilder class is a member of the BCL, in namespace System.Text .
￿A StringBuilder object is a mutable array of Unicode characters.
For example, the following code declares and initializes a string of type StringBuilder and
prints its value. The fourth line changes the actual object by replacing part of the string. Now,
when you print the value of the string, you can see that, unlike an object of type string , the
StringBuilder object has actually been changed.
using System.Text;
StringBuilder sb = new StringBuilder("Hi there.");
Console.WriteLine("{0}", sb); // Print string.
sb.Replace("Hi", "Hello"); // Replace a substring.
Console.WriteLine("{0}", sb); // Print changed string.
This code produces the following output:
Hi there.
Hello there.
When a StringBuilder object is created, the class allocates a buffer longer than the actual
current string length. As long as the changes made to the string can fit in the buffer, no new
memory is allocated. If changes to the string require more space than is available in the buffer,
a new, larger buffer is allocated, and the string is copied to it. Like the original buffer, this new
buffer also has extra space.
Search WWH ::




Custom Search