StringBuilders Explained

Visual Basic programmers have long enjoyed ease in string manipulations.
It is easy to create a string, split it up, concatenate multiple strings,
etc. For example, the following code sample illustrates how you could
append one string to another to become one:

Dim st As String
st = "Hello"
st += " World!"

However, this seemingly innocent piece of code is not the recommended
way to perform string manipulations in .NET. This is because strings
in NET are immutable, which means that once a string variable is assigned
a value, it cannot be changed. If the value of a string variable is
changed, another string object is created during runtime. In the above
code sample, two string objects are involved; one for the initialization
and one for the concatenation.

A more efficient way to manage strings is to use the StringBuilder
class available in the System.Text namespace. The StringBuilder
class represents a string-like object containing a string of characters.
It is much like the String data type, except that it is mutable -- the
content can be modified after creation.

The following code sample shows how to create a StringBuilder object.
One of the overloaded constructors takes in a string as a parameter.
You can simply treat this object as a string by using the ToString()
method:

Dim str As New StringBuilder("This is a string")
Dim aString As String
aString = str.ToString
Console.WriteLine(aString)

In the following sections, I will show you how to use the various methods
and properties in the StringBuilder class for some common string operations.

Appending a String

To append a string to an existing one, use the Append()
method:

'---Appending a string
str.Append(" created using StringBuilder.")
Console.WriteLine(str)

The above code gives the following output:

This is a string created using StringBuilder.

You can also apply text formatting to the text you want to append, using
the AppendFormat() method. In the following example, I
appended the current date (formatted using the ShortDatePattern format)
to the StringBuilder object.

'---Appending with format
str.AppendFormat("{0}:{1:d}", " Created on ", Today)
Console.WriteLine(str)

The above code gives the following output:

This is a string created using StringBuilder. Created on :7/14/2003

For more information on date formatting, please refer to the DataTimeFormatInfo class in MSDN.

Inserting a String

To insert a string, use the Insert() method:

'---Inserting a string
str.Insert(0, "VB.NET : ") ' insert into first position
Console.WriteLine(str)

The above code gives the following output:

VB.NET : This is a string created using StringBuilder. Created on :7/14/2003

C# : This is a string created using StringBuilder. Created on :7/14/2003

You can also replace a character, instead of a string, by using the
Chars() property with an index:

'---Replacing a character
str.Chars(0) = "c" ' replace the first char with "c"
Console.WriteLine(str)

The above code gives the following output:

c# : This is a string created using StringBuilder. Created on :7/14/2003

Removing a Sub-String

To remove a sub-string, use the Remove() method:

'---Removing a string
str.Remove(0, 5) ' start from first position and remove
' the next 5 chars
Console.WriteLine(str)

The above code gives the following output:

This is a string created using StringBuilder. Created on :7/14/2003

Finding the Index of a Word

Sometimes you need to find the position of a sub-string (or character)
within a string. In this case, you can use the IndexOf() method, together
with the ToString() method. If a sub-string cannot be found, it returns
the value -1.

'---Finding the index of first occurrence of a word
Console.WriteLine(str.ToString.IndexOf("i"))

The above code gives the following output:

2

The IndexOf() method returns the first occurrence of a given character
or string. To find all occurrences of a word, you need to use the
overloaded method of IndexOf() and put it within a loop. The following
example searches for the occurrence of the word "is" and then
continues searching from where it last found the word.

Overwriting and Truncating a String

You can assign a new string to a StringBuilder object by first removing
the entire line using the Remove() method and then using
the Append() method. The Length property returns the length
of the string:

The above code gives the following output (my comments are in parentheses):

-1 (str2 < str3)
1 (str3 > str4)
1 (str3 > str4)
0 (str3 = str4)

By default, string comparison is case-sensitive. If you want to ignore
case sensitivity when doing the comparison, use the overloaded Compare()
method, which takes in a Boolean value indicating if case should be ignored.
A value of True means case should be ignored. By default, the value
is False.