StringBuilder helps you build or change text efficiently without making many copies. It saves time and memory when you change text a lot.
StringBuilder and why it exists in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
C Sharp (C#)
StringBuilder sb = new StringBuilder(); sb.Append("Hello"); sb.Append(" World"); string result = sb.ToString();
Use Append to add text to the StringBuilder.
Use ToString() to get the final text after all changes.
Examples
C Sharp (C#)
StringBuilder sb = new StringBuilder(); sb.Append("Hi"); sb.Append(" there!"); string message = sb.ToString();
C Sharp (C#)
StringBuilder sb = new StringBuilder("Start"); sb.Append(" and continue"); string text = sb.ToString();
C Sharp (C#)
StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.Append(i); } string numbers = sb.ToString();
Sample Program
This program builds the text "Hello, world!" step by step using StringBuilder, then prints it.
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.Append("!"); string result = sb.ToString(); Console.WriteLine(result); } }
Important Notes
Strings in C# are immutable, meaning they cannot change once created. StringBuilder helps avoid making many copies.
Use StringBuilder when you expect many changes to text, otherwise simple string concatenation is fine.
Summary
StringBuilder helps build or change text efficiently.
It avoids creating many copies of strings, saving memory and time.
Use it when you add or change text many times, especially in loops.
Practice
1. Why does the
StringBuilder class exist in C#?easy
Solution
Step 1: Understand string immutability in C#
Strings cannot be changed once created, so modifying them creates new copies.Step 2: Role of StringBuilder
StringBuilder allows changing text without making many copies, saving memory and time.Final Answer:
To efficiently modify strings without creating many copies -> Option CQuick Check:
StringBuilder avoids many copies = A [OK]
Hint: StringBuilder avoids many string copies for efficiency [OK]
Common Mistakes:
- Thinking StringBuilder translates text
- Confusing StringBuilder with number storage
- Believing it speeds up math operations
2. Which of the following is the correct way to create a
StringBuilder instance in C#?easy
Solution
Step 1: Recall correct syntax for creating objects in C#
Use the 'new' keyword followed by the class name with parentheses.Step 2: Check each option
StringBuilder sb = new StringBuilder(); uses 'new StringBuilder()' correctly; others have syntax errors or wrong class names.Final Answer:
StringBuilder sb = new StringBuilder(); -> Option DQuick Check:
Correct object creation uses 'new ClassName()' = C [OK]
Hint: Use 'new' keyword with exact class name and parentheses [OK]
Common Mistakes:
- Omitting 'new' keyword
- Using lowercase class names
- Confusing StringBuilder with String
3. What will be the output of this C# code?
var sb = new StringBuilder();
sb.Append("Hi");
sb.Append(" there");
Console.WriteLine(sb.ToString());medium
Solution
Step 1: Understand Append method behavior
Append adds text to the existing StringBuilder content without spaces unless added explicitly.Step 2: Trace the code execution
First Append adds "Hi", second adds " there" (with space), so combined string is "Hi there".Final Answer:
Hi there -> Option AQuick Check:
Appending strings combines them exactly = D [OK]
Hint: Append joins text exactly as given, watch spaces [OK]
Common Mistakes:
- Assuming Append adds spaces automatically
- Expecting only first Append output
- Confusing newline characters
4. Identify the error in this code snippet using
StringBuilder:StringBuilder sb;
sb.Append("Hello");
Console.WriteLine(sb.ToString());medium
Solution
Step 1: Check variable initialization
StringBuilder sb is declared but not assigned an instance with 'new'.Step 2: Understand consequences
Calling Append on uninitialized sb causes runtime error (NullReferenceException).Final Answer:
StringBuilder is not initialized before use -> Option AQuick Check:
Uninitialized objects cause errors = B [OK]
Hint: Always initialize StringBuilder with 'new' before use [OK]
Common Mistakes:
- Forgetting to use 'new' keyword
- Thinking Append is missing
- Assuming ToString() is invalid
5. You want to build a string by adding numbers from 1 to 5 separated by commas using
StringBuilder. Which code snippet correctly does this without extra comma at the end?hard
Solution
Step 1: Analyze each option for comma placement
var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i); if(i < 5) sb.Append(","); } Console.WriteLine(sb.ToString()); adds number then comma only if not last, avoiding trailing comma.Step 2: Check other options
var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i + ","); } Console.WriteLine(sb.ToString()); adds comma after every number, causing extra comma at end; C adds comma before number, starting with comma; D hardcodes string, not using loop.Final Answer:
var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i); if(i < 5) sb.Append(","); } Console.WriteLine(sb.ToString()); -> Option BQuick Check:
Conditionally add commas to avoid trailing one = A [OK]
Hint: Add commas only between items, not after last [OK]
Common Mistakes:
- Adding comma after last item
- Adding comma before first item
- Hardcoding string instead of looping
