Thursday, March 25, 2021

StringBuilder in C#

StringBuilder is a mutable string class in C# that provides better performance than the standard string class when you need to perform multiple string manipulations.

Key features of StringBuilder:

  1. It's located in the System.Text namespace
  2. It's mutable (unlike string, which is immutable)
  3. More efficient for multiple string operations
  4. Particularly useful when concatenating many strings

Basic usage:


using System;
using System.Text;

class Program
{
    static void Main()
    {
        // Create a new StringBuilder
        StringBuilder sb = new StringBuilder();
        
        // Append text
        sb.Append("Hello");
        sb.Append(" ");
        sb.Append("World!");
        
        // Convert to string when done
        string result = sb.ToString();
        
        Console.WriteLine(result); // Outputs: Hello World!
    }
}

Common methods:

  • Append() - Adds text to the end
  • AppendLine() - Adds text with a line break
  • Insert() - Inserts text at a specified position
  • Remove() - Removes characters
  • Replace() - Replaces specified characters
  • Clear() - Removes all characters
  • ToString() - Converts to a string

StringBuilder is particularly valuable in loops or when you're building strings iteratively, as it avoids creating multiple string objects in memory.

Would you like me to explain any specific aspect of StringBuilder in more detail?

No comments:

Post a Comment