WindowsDevCenter.com
oreilly.comSafari Books Online.Conferences.

advertisement


AddThis Social Bookmark Button

StringBuilders Explained

by Wei-Meng Lee
07/21/2003

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.

Related Reading

Programming Visual Basic .NET
By Jesse Liberty

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

Replacing a String

Use the Replace() method to replace a string:


'---Replacing a string
'--case sensitive
str.Replace("VB.NET", "C#")  ' replace VB.NET 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

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.



'---Finding the index of all occurrences of a word
'--case sensitive
Dim index As Integer = -1
Do
	index += 1
	index = str.ToString.IndexOf("is", index)
	If index >= 0 Then Console.WriteLine(index)
Loop Until index = -1
   

The above code gives the following output:



2
5
   

Splitting a String

You can split a string into multiple sub-strings by using the Split() method supplied with a separator:



 '---Splitting a string
 Dim str1 As New _
	 StringBuilder("Mango Apple Orange Pineapple Durian")
 Dim aStr() As String = str1.ToString.Split(" ") ' separator is " "
 For j As Integer = 0 To aStr.Length - 1
	 Console.Write(aStr(j) & "-")
 Next
   

The above code gives the following output:



Mango-Peach-Orange-Pineapple-Durian-
   

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:



'---overwriting existing string
str1.Remove(0, str1.Length)
str1.Append("Mango Apple Orange Pineapple Durian")
Console.WriteLine(str1)
   

The above code gives the following output:



Mango Apple Orange Pineapple Durian
   

Instead of two separate statements, you can combine the above code example into one:



str1.Remove(0, str1.Length).Append("Mango Apple Orange Pineapple Durian")
Console.WriteLine(str1)
   

Another way would be to set the Length of the String Builder object to 0 (which essentially clears the string), and then use the Append() method:



str1.Length = 0
str1.Append("Mango Apple Orange Pineapple Durian")
Console.WriteLine(str1)
   

As you may have guessed it (or not, since you might expect the Length property to be read-only), setting the Length property to a value smaller than the actual length of a string truncates the string:


'---Truncating a string
str1.Length = 11
Console.WriteLine(str1)

The above code gives the following output:


Mango Apple

Comparing Strings

Another common operation with strings is comparison. You can compare the equality of strings using the Compare() method:


'---Comparing strings
Dim str2 As New StringBuilder("String 1")
Dim str3 As New StringBuilder("String 2")
Dim str4 As New StringBuilder("string 1")

Console.WriteLine(str2.ToString.Compare(str2.ToString, _
                                        str3.ToString))            
Console.WriteLine(str2.ToString.Compare(str2.ToString, _
                                        str4.ToString))        
Console.WriteLine(str2.ToString.Compare(str2.ToString, _
                                        str4.ToString, False)) 
Console.WriteLine(str2.ToString.Compare(str2.ToString, _
                                        str4.ToString, True))

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.

Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.


Return to ONDotnet.com