StringBuilder helps you build and change text quickly without making many copies. It is faster than using normal text when you change text many times.
0
0
StringBuilder methods and performance in C Sharp (C#)
Introduction
When you need to add or change text many times in a program.
When you want to join many small pieces of text into one big text.
When you want to avoid slow programs caused by changing normal text repeatedly.
When you want to build a message step-by-step before showing it.
When you want to improve performance in loops that create text.
Syntax
C Sharp (C#)
StringBuilder sb = new StringBuilder(); sb.Append("text"); sb.Insert(index, "more text"); sb.Remove(startIndex, length); sb.Replace("old", "new"); string result = sb.ToString();
StringBuilder is in the System.Text namespace, so you need using System.Text; at the top.
Use ToString() to get the final text from StringBuilder.
Examples
This adds two pieces of text and then gets the full text.
C Sharp (C#)
StringBuilder sb = new StringBuilder(); sb.Append("Hello"); sb.Append(" World"); string result = sb.ToString();
This starts with "Start" and inserts " Here" after it.
C Sharp (C#)
StringBuilder sb = new StringBuilder("Start"); sb.Insert(5, " Here"); string result = sb.ToString();
This replaces "World" with "C#" in the text.
C Sharp (C#)
StringBuilder sb = new StringBuilder("Hello World"); sb.Replace("World", "C#"); string result = sb.ToString();
This removes 3 characters starting at position 5.
C Sharp (C#)
StringBuilder sb = new StringBuilder("Hello C#"); sb.Remove(5, 3); string result = sb.ToString();
Sample Program
This program builds a greeting step-by-step using StringBuilder methods. It shows how Append, Insert, Replace, and Remove work together.
C Sharp (C#)
using System; using System.Text; class Program { static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Hello"); sb.Append(", "); sb.Append("world"); sb.Insert(5, " dear"); sb.Replace("world", "C#"); sb.Remove(10, 1); // remove space after 'dear' string result = sb.ToString(); Console.WriteLine(result); } }
OutputSuccess
Important Notes
StringBuilder is much faster than normal string when changing text many times.
Use StringBuilder when you have loops that add or change text repeatedly.
Remember to call ToString() to get the final text.
Summary
StringBuilder helps build text efficiently by changing it without making copies.
Use methods like Append, Insert, Replace, and Remove to change text.
Always convert to string with ToString() when done.