StringBuilder is a mutable string class in C# that allows efficient string manipulation without creating unnecessary objects. It is used for frequent concatenation, appending, or modification of strings.
The syntax for declaring and initializing a StringBuilder object in C# is as follows:
StringBuilder sb = new StringBuilder();
Here are some common methods of StringBuilder in C#:
- Append(): Appends a string or character to the end of the StringBuilder.
- Insert(): Inserts a string or character at the specified position in the StringBuilder.
- Remove(): Removes a specified number of characters from the StringBuilder, starting at a specified position.
- Replace(): Replaces all occurrences of a specified substring with a new string.
- Clear(): Clears all characters from the StringBuilder.
- ToString(): Converts the StringBuilder object to a string.
Here is source code of the C# Program to Illustrate StringBuilder. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/* * C# Program to Illustrate StringBuilder */ using System; using System.Text; class Program { static void Main() { StringBuilder bd = new StringBuilder(); bd.Append("1 "); bd.Append("2 "); bd.Append("3 "); for (int i = 0; i < 5; i++) { bd.Append("z "); } string result = bd.ToString(); Console.WriteLine(result); Console.ReadLine(); } }
1. This C# program illustrates the use of StringBuilder.
2. The Append() method appends a copy of the specified string to the StringBuilder.
3. Using a for loop, the value of ‘z‘ is appended multiple times.
4. The ToString() method is used to convert the StringBuilder’s character buffer into a string reference.
1 2 3 z z z z z
- Improved Performance: Efficiently handles string manipulations, enhancing speed.
- Reduced Memory Usage: Avoids unnecessary string object creations, saving memory.
- In-Place Modifications: Modifies strings without creating new instances.
- Streamlined Code: Cleaner and readable code for string operations.
- Faster Concatenation: Speeds up concatenation compared to alternatives, improving efficiency.
- Mutable Strings: Allows modification after creation for dynamic content.
- Efficient Loops: Performs well in loops and with large data.
- Suitable for Large Text: Handles large text or logs effectively.
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
- Check C# Books
- Check MCA Books
- Apply for Computer Science Internship
- Practice MCA MCQs
- Apply for C# Internship