C# StringBuilder

The C# StringBuilder class of .NET is a class to work with strings when repetitive string operations are needed. Use of strings in .NET could be a costly affair if not used property. 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. 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 in creates a StringBuilder object and appends 3 strings to it. 
  1. StringBuilder builder = new StringBuilder("Mahesh Chand");  
  2. builder.Append(", ");  
  3. builder.Append("Chris Love");  
  4. 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 10 strings. In the first part of the code, it uses a normal + operator to concatenate strings and the second part of the code uses a StringBuilder.
  1.    
  2. // Create a string and concatenate 10 strings  
  3. // Using + operator  
  4. string str = string.Empty;  
  5. DateTime startTime = DateTime.Now;  
  6. for (int i = 0; i < 10; i++)  
  7. {  
  8. str += i.ToString();  
  9. }  
  10. TimeSpan ts = DateTime.Now - startTime;  
  11. Console.WriteLine($"Execution time (10) using + operator: {ts.TotalMilliseconds}");  
  12.   
  13. // Concatenation using StringBuilder  
  14. StringBuilder builder = new StringBuilder();  
  15. startTime = DateTime.Now;  
  16. for (int i = 0; i < 10; i++)  
  17. {  
  18. builder.Append(i.ToString());  
  19. }  
  20. ts = DateTime.Now - startTime;  
  21. 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 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace StringBuilderClass  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             String MyName;  
  13.             StringBuilder MyOtherName = new StringBuilder("Hello");  
  14.             MyOtherName.Remove(2, 3); // produces "He"  
  15.             MyOtherName.Insert(2, "lp"); // produces "Help"  
  16.             MyOtherName.Replace('l''a'); // produces "Heap"  
  17.             MyName = MyOtherName.ToString();  
  18.         }  
  19.     }  
  20. }  
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-in operations like 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 you faster access to string literal 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 methods of the String class returns a new string as the result. 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 using the System.String class:
  1. string str1 = "I like ";  
  2. string str2 = "Soccer";  
  3. 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:
  1. StringBuilder MyStrBuilder = new StringBuilder("I like ");  
  2. String newStr = "Soccer";  
  3. MyStrBuilder.Append(newStr);  
The value of MyStrBuilder is I like Soccer.
 
You can use the String and StringBuilder classes whenever required and also 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 
  1. // Example IndexOf function for StringBuilder class  
  2.   
  3. using System;  
  4. using System.Text;  
  5.   
  6. public class App  
  7. {  
  8.     public static int sbIndexOf(StringBuilder sb, char ch)  
  9.     {  
  10.         Int32 intVal1 = -1;  
  11.         while (++intVal1 < sb.Length)  
  12.         {  
  13.             if (sb[intVal1] == ch)  
  14.             {  
  15.                 return intVal1;  
  16.             }  
  17.         }  
  18.         return -1;  
  19.     }  
  20.   
  21.     // string is an alias for System.String in the .NET Framework.  
  22.     public static void Main(string[] args)  
  23.     {  
  24.         StringBuilder sb1 = new StringBuilder(@"Hello There");  
  25.         Console.Write($"{App.sbIndexOf(sb1, 'o')}");  
  26.     }  
  27. }  
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 for use of the example on your computer.
 
Listing 3: StringBuilder Class
  1. //stringbuilder  
  2.   
  3. using System;  
  4. using System.Data;// for ADO.Net  
  5. using System.Data.SqlClient; // for SQL  
  6. using System.IO; // for FileStream class  
  7. using System.Text; // for StringBuilder class  
  8.   
  9. public class WriteXML  
  10. {  
  11.     public static void Main()  
  12.     {  
  13.   
  14.         // Build a connection  
  15.         SqlConnection myConn =  
  16.         new SqlConnection("server=vesnet27;uid=sa;pwd=;database=Pubs");  
  17.   
  18.         // Build the SQL string  
  19.         StringBuilder mySql = new StringBuilder("SELECT emp_id, fname, lname,hire_date ");  
  20.         mySql.Append("FROM employee ");  
  21.         mySql.Append("WHERE lname LIKE 'A%' ");  
  22.         mySql.Append("ORDER BY lname");  
  23.         Console.WriteLine(mySql);  
  24.   
  25.         // Build the DataSet Command object  
  26.         SqlCommand myCmd = new SqlCommand(mySql.ToString(), myConn);  
  27.   
  28.         // Build the DataSet  
  29.         DataSet myDs = new DataSet();  
  30.         SqlDataAdapter adapter = new SqlDataAdapter();  
  31.         adapter.SelectCommand = myCmd;  
  32.   
  33.         // Fill the DataSet with a dataset table named "Products"  
  34.         adapter.Fill(myDs);  
  35.   
  36.         // Get a FileStream object  
  37.         FileStream myFs =  
  38.         new FileStream("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);  
  39.   
  40.         // Use the WriteXml method of DataSet object to write an XML file from  
  41.         // the DataSet  
  42.         myDs.WriteXml(myFs);  
  43.         myFs.Close();  
  44.         Console.WriteLine("File Written");  
  45.     }  
  46.   
The program in Listing 4, has this output: 
 
StringBuilderClass
 
Conclusion
 
Hope this article would have helped you in understanding 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