C# StringBuilder Tutorial With Code Examples

C# StringBuilder class of .NET is a class to work with strings when repetitive string operations are needed. Use o this class could be a costly affair if not used properly. Strings being immutable objects, any modification of a string object creates a new string object. The StringBuilder is the optimal way to write code when multiple string manipulation operations take place in code.

StringBuilder class is defined in the System.Text namespace. You must either import this namespace in your class or reference it directly in the object instantiation.

using System.Text;

StringBuilder class in .NET provides several methods for string manipulation methods. First, let’s look at the StringBuilder class methods. 

  1. StringBuilder.Append Appends string to the end of the current StringBuilder.
  2. StringBuilder.AppendFormat Replaces a format specifier passed in a string with formatted text.
  3. StringBuilder.Insert Inserts a string or object into the specified index of the current StringBuilder.
  4. StringBuilder.Remove Removes a specified number of characters from the current StringBuilder.
  5. StringBuilder.Replace Replaces a specified character at a specified index.

The following code snippet creates a StringBuilder object and appends three strings to it. 

StringBuilder builder = new StringBuilder("Mahesh Chand");  
builder.Append(", ");  
builder.Append("Chris Love");  
builder.Append(", Praveen Kumar"); 

StringBuilder and Performance

StringBuilder can improve the performance of your code if string concatenation is needed more than a few times. The code example in Listing 3 concatenates ten strings. The first part of the code uses a normal + operator to concatenate strings, and the second part of the code uses a StringBuilder.

// Create a string and concatenate 10 strings  
// Using + operator  
string str = string.Empty;  
DateTime startTime = DateTime.Now;  
for (int i = 0; i < 10; i++)  
str += i.ToString();  
TimeSpan ts = DateTime.Now - startTime;  
Console.WriteLine($"Execution time (10) using + operator: {ts.TotalMilliseconds}");  
// Concatenation using StringBuilder  
StringBuilder builder = new StringBuilder();  
startTime = DateTime.Now;  
for (int i = 0; i < 10; i++)  
ts = DateTime.Now - startTime;  
Console.WriteLine($"Execution time (10) using SB: {ts.TotalMilliseconds}");

Listing 3.

The result of Listing 3 looks like the following in milliseconds. As you can see, StringBuilder is much faster.

Execution time (10) using + operator: 2.6742

Execution time (10) using SB: 0.0051

Now, let’s try the same operation 1000 times by changing the for loop from 0 to 1000. The new results look like the following.

Execution time (1000) using + operator: 4.5812

Execution time (1000) using SB: 0.1177

Both String and StringBuilder contain Unicode characters of type Char and support an indexer that returns Char. Because the String class is immutable, its indexer is read-only, but the StringBuilder indexer is readable/writeable. Listing 1 illustrates how to manipulate characters with the StringBuilder class and then place the characters into a string object.

Listing 1: StringBuilder string manipulation

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace StringBuilderClass  
    class Program  
        static void Main(string[] args)  
            String MyName;  
            StringBuilder MyOtherName = new StringBuilder("Hello");  
            MyOtherName.Remove(2, 3); // produces "He"  
            MyOtherName.Insert(2, "lp"); // produces "Help"  
            MyOtherName.Replace('l', 'a'); // produces "Heap"  
            MyName = MyOtherName.ToString();  

You can use either String or StringBuilder for string operations. Deciding which to use depends on the frequency of the string modification. If you modify the string frequently, such as reassigning, appending, removing, and replacing some characters, you should choose the StringBuilder class. However, if your methods do not change the string value much, registering the String class to the .NET Framework's internal string table will save space in memory for duplicate strings. The framework also provides faster access to literal string values stored in variables. The .NET Framework automatically handles these operations behind the scenes for you.

For example, whenever you modify a string in the String class, the String class methods return a new string. Therefore, creating many String objects might degrade the performance of your program. You can avoid creating a new instance of a string by using the StringBuilder class.

Let's say you want to concatenate two strings. Here is the traditional way of using the System.String class:

string str1 = "I like ";  
string str2 = "Soccer";  
string strConcat = string.Concat(str1, str2);  

The value of strConcat is I like Soccer. You can use the StringBuilder class and its Append method to do the same thing:

StringBuilder MyStrBuilder = new StringBuilder("I like ");  
String newStr = "Soccer";  

The value of MyStrBuilder is I like Soccer.

You can use the String and StringBuilder classes whenever required and write auxilliary functions for both classes by providing static helper functions. For example, by default StringBuilder does not provide the IndexOf member function, which does a linear search for a character in a string. But Listing 2 shows how you can create your own custom IndexOf function.

Listing 2: StringBuilder IndexOf

// Example IndexOf function for StringBuilder class  
using System;  
using System.Text;  
public class App  
    public static int sbIndexOf(StringBuilder sb, char ch)  
        Int32 intVal1 = -1;  
        while (++intVal1 < sb.Length)  
            if (sb[intVal1] == ch)  
                return intVal1;  
        return -1;  
    // string is an alias for System.String in the .NET Framework.  
    public static void Main(string[] args)  
        StringBuilder sb1 = new StringBuilder(@"Hello There");  
        Console.Write($"{App.sbIndexOf(sb1, 'o')}");  

Listing 3 illustrates StringBuilder usage when building SQL queries. The code segment connects to a Microsoft SQL Server Pubs database, which is installed by default as an example database with predefined options. You'll need to change the SqlClient constructor to use the example on your computer.

Listing 3: StringBuilder Class

using System;  
using System.Data;// for ADO.Net  
using System.Data.SqlClient; // for SQL  
using System.IO; // for FileStream class  
using System.Text; // for StringBuilder class  
public class WriteXML  
    public static void Main()  
        // Build a connection  
        SqlConnection myConn =  
        new SqlConnection("server=vesnet27;uid=sa;pwd=;database=Pubs");  
        // Build the SQL string  
        StringBuilder mySql = new StringBuilder("SELECT emp_id, fname, lname,hire_date ");  
        mySql.Append("FROM employee ");  
        mySql.Append("WHERE lname LIKE 'A%' ");  
        mySql.Append("ORDER BY lname");  
        // Build the DataSet Command object  
        SqlCommand myCmd = new SqlCommand(mySql.ToString(), myConn);  
        // Build the DataSet  
        DataSet myDs = new DataSet();  
        SqlDataAdapter adapter = new SqlDataAdapter();  
        adapter.SelectCommand = myCmd;  
        // Fill the DataSet with a dataset table named "Products"  
        // Get a FileStream object  
        FileStream myFs =  
        new FileStream("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);  
        // Use the WriteXml method of DataSet object to write an XML file from  
        // the DataSet  
        Console.WriteLine("File Written");  

The program in Listing 4, has this output: 



This article helped you understand the StringBuilder Class in C#. See other articles on the website on .NET and C#.

Here is another article on String Builder: String Builder and String Concatenation 

Similar Articles