The System TextString Builder Type

Given that the String type can be quite 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, StringBuilder defines methods that allow you to replace or format segments and so forth.

What is unique about StringBuilder is that when you call members of StringBuilder, you are directly modifying the object's internal character data, not obtaining a copy of the data in a modified format (and it is thus more efficient). When you create an instance of StringBuilder, you will supply the object's initial startup values via one of many constructors. Chapter 5 dives into the details of class constructors; however, if you are new to the topic, 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:

Imports System.Text ' StringBuilder lives here!

Module Program Sub Main()

' Use the StringBuilder.

Dim sb As New StringBuilder("**** Fantastic Games ****") sb.Append(vbLf)

sb.AppendLine("Half Life 2") sb.AppendLine("Beyond Good and Evil") sb.AppendLine("Deus Ex 1 and 2") sb.Append("System Shock") sb.Replace("2", "Deus Ex: Invisible War") Console.WriteLine(sb)

Console.WriteLine("sb has {0} chars.", sb.Length) End Sub End Module

Here we see 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 hold a string of 16 characters or less; however, this initial value can be changed via a constructor argument. While the buffer will expand automatically when needed, this might not be particularly efficient if you know the buffer will need to be quite large, so a more efficient approach is to create the buffer with a bigger size from the outset:

' Make a StringBuilder with an initial size of 256.

Dim sb As New StringBuilder("**** Fantastic Games ****", 256)

Again, if you append more characters than the specified limit, the StringBuilder object will copy its data into a new instance and grow the buffer by the specified limit.

Source Code The FunWithStrings project is located under the Chapter 3 subdirectory.

Was this article helpful?

0 0

Post a comment