StringBuilder in C# with Examples

С# StringBuilder is similаr tо Jаvа StringBuilder. А String оbjeсt is immutаble, it means string саnnоt be сhаnged оnсe сreаted. Every time when yоu use аny оf the methоds оf the System.String сlаss, yоu have to сreаte а new string оbjeсt each time. To solve this problem, C# introducted StringBuilder.

Syntax:

StringBuilder stringBuilder = new StringBuilder();

You can access the StringBuilder class from the System.Text namespace in C#. The StringBuilder will not create a new object each time but dynamically expands memory to accommodate the modified string.

Creating a StringBuilder Object

You can use new keyword to create an object of StringBuilder class as shown below,

Example:

StringBuilder stringBuilder = new StringBuilder("TechieClues is a developer Community");

Retrieve String from StringBuilder

StringBuilder is an object and not an actual string so we have to use ToString() method to convert the object to a string value as shown below,

StringBuilder stringBuilder = new StringBuilder("TechieClues is a developer Community");
Console.WriteLine(stringBuilder.ToString());

Output:

TechieClues is a developer Community       

Imроrtаnt  Methоds  оf  StringBuilder:

  • Аррend(string  vаlue)
  • АррendFоrmаt()
  • Insert(int  index,  string  vаlue)
  • Remоve(int  stаrt,  int  length)
  • Reрlасe(оld_vаlue,  new_vаlue)

Append() Method in C#

The append method adds a string, substring, character array, part of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a StringBuilder object.

Example:

// Creating a StringBuilder Object
StringBuilder stringBuilder = new StringBuilder();

// Append string using Append() method
stringBuilder.Append("Ford");
stringBuilder.Append("Audi");
stringBuilder.Append("Tesla");
stringBuilder.Append("BMW");

// Print string value
Console.WriteLine(stringBuilder);

Output:

FordAudiTeslaBMW

AppendLine() Method in C#

The AppendLine method adds a line terminator or a string with a line terminator to a StringBuilder object.

Example:

// Creating a StringBuilder Object
StringBuilder stringBuilder = new StringBuilder();

// Append string using AppendLine() method
stringBuilder.AppendLine("Ford");
stringBuilder.AppendLine("Audi");
stringBuilder.AppendLine("Tesla");
stringBuilder.AppendLine("BMW");

// Print string value
Console.WriteLine(stringBuilder);

Output:

Ford
Audi
Tesla
BMW

Capacity of StringBuilder

StringBuilder is а dynаmiс оbjeсt thаt аllоws yоu tо exраnd the number оf сhаrасters in the string thаt it enсарsulаtes, yоu саn sрeсify а vаlue fоr the mаximum number оf сhаrасters thаt it саn hоld. This vаlue is саlled the сарасity оf the StringBuilder оbjeсt.

Syntax:

StringBuilder stringBuilder = new StringBuilder(2);

Insert() Method in C#

The Insert method inserts a string, substring, multiple repetitions of a string, a series of characters, part of a series of characters, or the string representation of a primitive data type at a specific position in the StringBuilder object. The position is determined by a zero-based index.

Example:

// Creating a StringBuilder Object
StringBuilder stringBuilder = new StringBuilder("TechieClues is a developer community");

// Insert the "--" after Techieclues
stringBuilder.Insert(11, " --");

// Print string value
Console.WriteLine(stringBuilder);

Output:

TechieClues -- is a developer community

Remove() Method in C#

The Remove method removes a certain number of characters starting at a certain index position. In addition, you can remove characters from the end of a StringBuilder object by setting the Length property to a value that is less than the length of the current instance.

Example:

// Creating a StringBuilder Object
StringBuilder stringBuilder = new StringBuilder("TechieClues is a developer community");

// Remove "is a" chars from the string. So we use starting index and length
stringBuilder.Remove(12, 5);

// Print string value
Console.WriteLine(stringBuilder);

Output:

TechieClues developer community

Replace() Method in C#

In C# for replacing the Specific Character with another character, there's a method StringBuilder.Replace();

Example:

// Creating a StringBuilder Object
StringBuilder stringBuilder = new StringBuilder("TechieClues is a developer community");

// Replace the string
stringBuilder.Replace("developer community", "learning portal");

// Print string value
Console.WriteLine(stringBuilder);

Output

TechieClues is a learning portal

Properties

Property Usage
Capacity Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.
Chars[Int32] Gets or sets the character at the specified character position in this instance.
Length Gets or sets the length of the current StringBuilder object.
MaxCapacity Gets the maximum capacity of this instance.

Methods

Method Usage
Append(Boolean) Appends the string representation of a specified Boolean value to this instance.
Append(Byte) Appends the string representation of a specified 8-bit unsigned integer to this instance.
Append(Char) Appends the string representation of a specified Char object to this instance.
Append(Char*, Int32) Appends an array of Unicode characters starting at a specified address to this instance.
Append(Char, Int32) Appends a specified number of copies of the string representation of a Unicode character to this instance.
Append(Char[]) Appends the string representation of the Unicode characters in a specified array to this instance.
Append(Char[], Int32, Int32) Appends the string representation of a specified subarray of Unicode characters to this instance.
Append(Decimal) Appends the string representation of a specified decimal number to this instance.
Append(Double) Appends the string representation of a specified double-precision floating-point number to this instance.
Append(Int16) Appends the string representation of a specified 16-bit signed integer to this instance.
Append(Int32) Appends the string representation of a specified 32-bit signed integer to this instance.
Append(Int64) Appends the string representation of a specified 64-bit signed integer to this instance.
Append(Object) Appends the string representation of a specified object to this instance.
Append(ReadOnlyMemory<Char>) Appends the string representation of a specified read-only character memory region to this instance.
Append(ReadOnlySpan<Char>) Appends the string representation of a specified read-only character span to this instance.
Append(SByte) Appends the string representation of a specified 8-bit signed integer to this instance.
Append(Single) Appends the string representation of a specified single-precision floating-point number to this instance.
Append(String) Appends a copy of the specified string to this instance.
Append(String, Int32, Int32) Appends a copy of a specified substring to this instance.
Append(StringBuilder) Appends the string representation of a specified string builder to this instance.
Append(StringBuilder, Int32, Int32) Appends a copy of a substring within a specified string builder to this instance.
Append(UInt16) Appends the string representation of a specified 16-bit unsigned integer to this instance.
Append(UInt32) Appends the string representation of a specified 32-bit unsigned integer to this instance.
Append(UInt64) Appends the string representation of a specified 64-bit unsigned integer to this instance.
AppendFormat(IFormatProvider, String, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument using a specified format provider.
AppendFormat(IFormatProvider, String, Object, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of either of two arguments using a specified format provider.
AppendFormat(IFormatProvider, String, Object, Object, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of either of three arguments using a specified format provider.
AppendFormat(IFormatProvider, String, Object[]) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider.
AppendFormat(String, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a single argument.
AppendFormat(String, Object, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of either of two arguments.
AppendFormat(String, Object, Object, Object) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of either of three arguments.
AppendFormat(String, Object[]) Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a corresponding argument in a parameter array.
AppendJoin(Char, Object[]) Concatenates the string representations of the elements in the provided array of objects, using the specified char separator between each member, then appends the result to the current instance of the string builder.
AppendJoin(Char, String[]) Concatenates the strings of the provided array, using the specified char separator between each string, then appends the result to the current instance of the string builder.
AppendJoin(String, Object[]) Concatenates the string representations of the elements in the provided array of objects, using the specified separator between each member, then appends the result to the current instance of the string builder.
AppendJoin(String, String[]) Concatenates the strings of the provided array, using the specified separator between each string, then appends the result to the current instance of the string builder.
AppendJoin<T>(Char, IEnumerable<T>) Concatenates and appends the members of a collection, using the specified char separator between each member.
AppendJoin<T>(String, IEnumerable<T>) Concatenates and appends the members of a collection, using the specified separator between each member.
AppendLine() Appends the default line terminator to the end of the current StringBuilder object.
AppendLine(String) Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.
Clear() Removes all characters from the current StringBuilder instance.
CopyTo(Int32, Char[], Int32, Int32) Copies the characters from a specified segment of this instance to a specified segment of a destination Char array.
CopyTo(Int32, Span<Char>, Int32) Copies the characters from a specified segment of this instance to a destination Char span.
EnsureCapacity(Int32) Ensures that the capacity of this instance of StringBuilder is at least the specified value.
Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object)
Equals(ReadOnlySpan<Char>) Returns a value indicating whether the characters in this instance are equal to the characters in a specified read-only character span.
Equals(StringBuilder) Returns a value indicating whether this instance is equal to a specified object.
GetChunks() Returns an object that can be used to iterate through the chunks of characters represented in a ReadOnlyMemory<Char> created from this StringBuilder instance.
GetHashCode() Serves as the default hash function. (Inherited from Object)
GetType() Gets the Type of the current instance. (Inherited from Object)
Insert(Int32, Boolean) Inserts the string representation of a Boolean value into this instance at the specified character position.
Insert(Int32, Byte) Inserts the string representation of a specified 8-bit unsigned integer into this instance at the specified character position.
Insert(Int32, Char) Inserts the string representation of a specified Unicode character into this instance at the specified character position.
Insert(Int32, Char[]) Inserts the string representation of a specified array of Unicode characters into this instance at the specified character position.
Insert(Int32, Char[], Int32, Int32) Inserts the string representation of a specified subarray of Unicode characters into this instance at the specified character position.
Insert(Int32, Decimal) Inserts the string representation of a decimal number into this instance at the specified character position.
Insert(Int32, Double) Inserts the string representation of a double-precision floating-point number into this instance at the specified character position.
Insert(Int32, Int16) Inserts the string representation of a specified 16-bit signed integer into this instance at the specified character position.
Insert(Int32, Int32) Inserts the string representation of a specified 32-bit signed integer into this instance at the specified character position.
Insert(Int32, Int64) Inserts the string representation of a 64-bit signed integer into this instance at the specified character position.
Insert(Int32, Object) Inserts the string representation of an object into this instance at the specified character position.
Insert(Int32, ReadOnlySpan<Char>) Inserts the sequence of characters into this instance at the specified character position.
Insert(Int32, SByte) Inserts the string representation of a specified 8-bit signed integer into this instance at the specified character position.
Insert(Int32, Single) Inserts the string representation of a single-precision floating point number into this instance at the specified character position.
Insert(Int32, String) Inserts a string into this instance at the specified character position.
Insert(Int32, String, Int32) Inserts one or more copies of a specified string into this instance at the specified character position.
Insert(Int32, UInt16) Inserts the string representation of a 16-bit unsigned integer into this instance at the specified character position.
Insert(Int32, UInt32) Inserts the string representation of a 32-bit unsigned integer into this instance at the specified character position.
Insert(Int32, UInt64) Inserts the string representation of a 64-bit unsigned integer into this instance at the specified character position.
MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object)
Remove(Int32, Int32) Removes the specified range of characters from this instance.
Replace(Char, Char) Replaces all occurrences of a specified character in this instance with another specified character.
Replace(Char, Char, Int32, Int32) Replaces, within a substring of this instance, all occurrences of a specified character with another specified character.
Replace(String, String) Replaces all occurrences of a specified string in this instance with another specified string.
Replace(String, String, Int32, Int32) Replaces, within a substring of this instance, all occurrences of a specified string with another specified string.
ToString() Converts the value of this instance to a String.
ToString(Int32, Int32) Converts the value of a substring of this instance to a String.