C#

C# StringBuilder

The objective of this article is to familiarize you with the C# StringBuilder. C# StringBuilder class is a better alternative when building a large number of strings in multiple steps that needs to be modified many times during the process.

You will learn

C# StringBuilder represents a mutable (editable) string class defined in the System.Text namespace. With this class, you can directly change the content of a string object, which provides better performance than the traditional way of System.String class, where any change applied to a string do not modify it instead return a new string object in a modified format.

StringBuilder Methods and Properties

C# StringBuilder class provides useful methods and properties to help us manipulate the content of a string very easily and efficiently. The most important are listed below.

C# StringBuilder Properties

Property Description
Length Returns the number of characters in the StringBuilder.
Capacity Retrieves or sets the number of characters the StringBuilder can hold in the buffer.
MaxCapacity Returns the maximum capacity of the StringBuilder.
[index] Indexer returns the character at the specified position in the StringBuilder.

C# StringBuilder Methods

Method Description
Append() Appends a string after the last character of the current string.
Insert() Inserts a substring at the specified position into the current string.
Replace() Replaces all occurrences of a given substring or character with new substring or character in the current string.
Remove() Removes the specified characters from the current string.
Clear() Removes all characters from the current string.
ToString() Converts the value of an object to a regular string.

using Statement

To work with the C# StringBuilder, you need to add the following namespace at the beginning of your code:

using System.Text;

C# StringBuilder Declaration and Initialization

You use new keyword with default constructor to initialize an empty StringBuilder to be stored temporarily in the sb variable. This is how you create an object from the StringBuilder class:

1 – Constructor Signature: StringBuilder();

StringBuilder sb = new StringBuilder();

StringBuilder constructor optionally takes initial string as a parameter to create a new instance of the StringBuilder class as follows:

Note: Initial capacity might differ from the string’s size (default is 16 characters).

2 – Constructor Signature: StringBuilder(string value);

string myString = "Hi, Pirzada";
StringBuilder sb = new StringBuilder(myString);
// OR
StringBuilder sb = new StringBuilder("Hi, Pirzada");

You can use another constructor, which accepts capacity as an argument to initialize empty StringBuilder.

3 – Constructor Signature: StringBuilder(int capacity);

StringBuilder sb = new StringBuilder(7);

You can explicitly set the initial string and capacity of a StringBuilder object by calling the following constructor.

Constructor Signature: StringBuilder(string value, int capacity);

StringBuilder sb = new StringBuilder("Hello", 7);

Once you are done with string manipulation, than call ToString method to convert StringBuilder object into a regular string.

string finalString = sb.ToString();
Console.WriteLine(finalString);

Run Demo

Length, Capacity, MaxCapacity, and Indexer Properties

Let’s look at the examples.

Length

C# StringBuilder Length property gets or sets the length of the current StringBuilder object.
Note: Length doesn’t change the Capacity.

StringBuilder sb = new StringBuilder("Hi, Pirzada");
Console.WriteLine(sb.Length); // Prints 11
StringBuilder sb = new StringBuilder("Hi, Pirzada");
Console.WriteLine(sb.Length); // Current Length is 11

Let’s decrease the StringBuilder length from 11 to 2.

sb.Length = 2;

If the target length is less than the StringBuilder’s total number of characters, the contents are truncated to adjust the target length.

Console.WriteLine(sb.Length); // Now Current Length is 2
Console.WriteLine(sb.ToString()); // Prints Hi
StringBuilder sb = new StringBuilder("Hi, Pirzada");
Console.WriteLine(sb.Length); // Current Length is 11

Let’s increase the StringBuilder length from 11 to 14.

sb.Length = 14;

If the target length is greater than the StringBuilder’s current number of characters, null characters are appended until the target length is achieved.

Console.WriteLine(sb.Length); // Now Current Length is 14
Console.WriteLine(sb.ToString()); // Prints Hi, Pirzada

Run Demo

Capacity

Gets or sets the number of characters that the object can hold in the memory, use C# StringBuilder Capacity property.

The default capacity of a StringBuilder is 16 characters; if initialized without specifying the capacity. As you can see in the following example.

Note: Default MaxCapacity of StringBuilder is Int32.MaxValue, which is 2147483647.

StringBuilder sb = new StringBuilder(); 
Console.WriteLine(sb.Capacity); // default capacity 16
Console.WriteLine(sb.MaxCapacity); // max capacity 2147483647

The capacity automatically assigned to a StringBuilder is 16, even if initialized with a single character. As soon as the number of characters exceeds 16, the StringBuilder object is resized to accommodate additional characters. With every resize the capacity is automatically doubled from 16 to 32, 64, 128 etc. Check the below example.

StringBuilder sb = new StringBuilder(); 
Console.WriteLine(sb.Capacity); // default capacity 16
sb.Append("Hello, Pirzada Rashid");
Console.WriteLine(sb.Capacity); // capacity doubled 32

Run Demo

If you set the capacity during or after initialization of a StringBuilder object and the number of characters exceeds that capacity, an ArgumentOutOfRangeException exception is raised mentioning 'capacity was less than the current size.’

StringBuilder sb = new StringBuilder(); 
sb.Append("Hello");

The capacity of current object is 16 and length is 5 characters. Let’s set the capacity less than the current length of the StringBuilder.

sb.Capacity = 2; // throw exception

Run Demo

You can also use constructor that takes an int argument as the initial capacity to create an empty StringBuilder. As characters are added to the StringBuilder object, the capacity is automatically increased to hold more characters. The capacity is doubled if required. This way you can save unnecessary dynamic memory allocations.

Constructor Signature: StringBuilder (int capacity);

StringBuilder sb = new StringBuilder(6); 
Console.WriteLine(sb.Capacity); // current capacity 6
sb.Append("Hi, Pirzada");
Console.WriteLine(sb.Capacity); // doubled capacity 12

Run Demo

As you know C# StringBuilder capacity is automatically doubled at a certain point to accommodate more characters. This increase in capacity might differ when initialized as a constructor argument. Consider the following example.

StringBuilder sb = new StringBuilder("123456", 5);
Console.WriteLine(sb.Length); // 6
Console.WriteLine(sb.Capacity); // capacity equal to length : 6
sb.Append("78901234567");
Console.WriteLine(sb.Length); // 17
Console.WriteLine(sb.Capacity); // capacity equal to length : 17
Console.WriteLine(sb.ToString());
StringBuilder sb = new StringBuilder(5);
Console.WriteLine(sb.Capacity); // initial capacity : 5
sb.Append("123456");
Console.WriteLine(sb.Length); // 6
Console.WriteLine(sb.Capacity); // capacity doubled : 10
Console.WriteLine(sb.ToString());

Run Demo

MaxCapacity

C# StringBuilder MaxCapacity is a read-only property that indicates the limit to which StringBuilder object can store maximum number of characters in the memory. By default, MaxCapacity is specified by Int32.MaxValue (2147483647).

The maximum number of characters the current StringBuilder object can contain.

StringBuilder sb = new StringBuilder(); 
Console.WriteLine(sb.MaxCapacity); // Prints 2147483647

You can explicitly set the maximum capacity of a StringBuilder object by calling the constructor.

Constructor Signature: StringBuilder (int capacity, int maxCapacity);

StringBuilder sb = new StringBuilder(3,7);

This will set the initial capacity to 3, but the maximum capacity assigned to it is 7. This means, StringBuilder can never grow more than 7 characters. The StringBuilder object does not allocate additional memory, but instead raise ArgumentOutOfRangeException exception with the message 'capacity was less than the current size.’

sb.Append("Code"); // no problem
sb.Append("buns"); // throw exception
Console.WriteLine(sb.ToString());

Run Demo

Append(), Insert(), Replace(), Remove(), and Clear() Methods

Let’s look at the examples.

Append()

C# StringBuilder Append method appends the specified string to the end of the current StringBuilder object.

Method Signature: StringBuilder Append (string value);

Note: The capacity of the object is adjusted as needed.

The append method returns the StringBuilder object on which append is invoked. This means you can chain calls to append to add more strings.

StringBuilder sb = new StringBuilder(); 
sb.Append("Hi, Mr");
sb.Append(" Pirzada");
Console.WriteLine(sb.ToString());

Run Demo

OUTPUT

Hi, Mr Pirzada

Insert()

C# StringBuilder Insert method inserts the specified string at a specified position in a StringBuilder.

Method Signature: StringBuilder Insert (int index, string value);

Note: Existing characters are shifted to make room for the new text. The capacity is adjusted as needed.

StringBuilder sb = new StringBuilder("Hi, Pirzada"); 
sb.Insert(4, "Mr ");
Console.WriteLine(sb.ToString());
OUTPUT

Hi, Mr Pirzada

I have a StringBuilder object, which contains the value “1234678”. Insert the letter 5 after the 4. Print the modified StringBuilder out.

StringBuilder sb = new StringBuilder("1234678");       
sb.Insert(4, '5');       
Console.WriteLine(sb.ToString());
OUTPUT

12345678

Run Demo

Replace()

C# StringBuilder Replace method searches for a specified string or character and replaces all occurrences of it with another string or character.

StringBuilder sb = new StringBuilder("Hi, Pirzada");

1 – Method Signature: StringBuilder Replace (string oldValue, string newValue);

Note: case-sensitive comparison.

sb.Replace("Hi", "Hello");
Console.WriteLine(sb.ToString());
OUTPUT

Hello, Pirzada

2 – Method Signature: StringBuilder Replace (string oldValue, string newValue, int startIndex, int count);

Note: case-sensitive comparison.

sb.Replace("i", "ello", 1, 4);
Console.WriteLine(sb.ToString());
OUTPUT

Hello, Pirzada

Run Demo

Remove()

C# StringBuilder Remove method deletes the specified range of characters from the StringBuilder object.

Method Signature: StringBuilder Remove (int startIndex, int length);
Remove method takes two arguments—the index at which to start removal and the number of characters to remove.

Note: The string value of the current object is shortened by length. The capacity is unaffected.

StringBuilder sb = new StringBuilder("Hi, Pirzada"); 
sb.Remove(0, 4);
Console.WriteLine(sb.ToString());

Run Demo

OUTPUT

Pirzada

Clear()

C# StringBuilder Clear method removes all the characters and sets its Length property to zero.

Note: Setting the current object Length to zero doesn’t shrink its internal capacity.

StringBuilder sb = new StringBuilder("Hi, Pirzada"); 
Console.WriteLine(sb.Length); // length before clear is 11
sb.Clear();
Console.WriteLine(sb.Length); // length after clear is 0

Run Demo

Access Individual StringBuilder Character

You can display the StringBuilder characters individually by using an indexer, which must be an integer type. The index position is used inside the square brackets [ ] when retrieving the character from the object. The first character can be accessed with an index value of 0.

StringBuilder sb = new StringBuilder("Hi, Pirzada"); 
Console.WriteLine(sb[6]); // Prints r

You can use writable indexer for setting individual characters, like this:

sb[10] = 'o';
Console.WriteLine(sb[10]); // Prints o

If you try to access character with an indexer and pass an index that does not exist, an exception of type IndexOutOfRangeException is thrown with the message 'Index was outside the bounds of the array'.

Console.WriteLine(sb[11]); // throw exception

Run Demo

Useful Articles

C# Reference | Microsoft Docs

Sending
User Rating 0 (0 vote)
Tagged in :

Add Comment

Click here to post a comment

Send this to a friend