Bird
Raised Fist0
C Sharp (C#)programming~20 mins

StringBuilder methods and performance in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
StringBuilder Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of StringBuilder Append and Insert
What is the output of this C# code snippet?
C Sharp (C#)
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder("Hello");
        sb.Append(" World");
        sb.Insert(5, ",");
        Console.WriteLine(sb.ToString());
    }
}
AHello, World
BHello World,
CHello World
DHello,World
Attempts:
2 left
💡 Hint
Remember that Insert adds characters at the specified index without removing existing ones.
Predict Output
intermediate
2:00remaining
StringBuilder Replace method effect
What will be printed by this code?
C Sharp (C#)
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder("abracadabra");
        sb.Replace("a", "o", 3, 5);
        Console.WriteLine(sb.ToString());
    }
}
Aabrocodobro
Babrocodobra
Cobrocodobro
Dobrocadobra
Attempts:
2 left
💡 Hint
Replace only affects the substring starting at index 3 for length 5.
Predict Output
advanced
2:00remaining
Performance difference between string concatenation and StringBuilder
What is the expected output of this code snippet?
C Sharp (C#)
using System;
using System.Text;
using System.Diagnostics;

class Program {
    static void Main() {
        int n = 10000;
        Stopwatch sw = new Stopwatch();

        sw.Start();
        string s = "";
        for (int i = 0; i < n; i++) {
            s += i.ToString();
        }
        sw.Stop();
        Console.WriteLine("String concat time: " + sw.ElapsedMilliseconds + "ms");

        sw.Reset();
        sw.Start();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.Append(i.ToString());
        }
        string result = sb.ToString();
        sw.Stop();
        Console.WriteLine("StringBuilder time: " + sw.ElapsedMilliseconds + "ms");
    }
}
AString concat time: much greater than StringBuilder time
BString concat time: much less than StringBuilder time
CBoth times are about the same
DCode throws an exception due to memory overflow
Attempts:
2 left
💡 Hint
String concatenation creates many intermediate strings, while StringBuilder modifies in place.
Predict Output
advanced
2:00remaining
Effect of Capacity and Length on StringBuilder
What will be the output of this code?
C Sharp (C#)
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder(5);
        Console.WriteLine(sb.Capacity);
        sb.Append("HelloWorld");
        Console.WriteLine(sb.Capacity);
        sb.Length = 5;
        Console.WriteLine(sb.ToString());
    }
}
A
5
20
HelloWorld
B
5
10
Hello
C
5
16
Hello
D
5
16
HelloWorld
Attempts:
2 left
💡 Hint
Capacity grows automatically when exceeded. Length truncates the string.
Predict Output
expert
2:00remaining
StringBuilder Thread Safety and Exception
What happens when this code runs?
C Sharp (C#)
using System;
using System.Text;
using System.Threading.Tasks;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder();
        Parallel.For(0, 1000, i => {
            sb.Append(i);
        });
        Console.WriteLine(sb.Length);
    }
}
APrints a number close to 2893 without error
BThrows a System.ArgumentOutOfRangeException
CThrows a System.IndexOutOfRangeException
DThrows a System.InvalidOperationException
Attempts:
2 left
💡 Hint
StringBuilder is not thread-safe for concurrent writes.

Practice

(1/5)
1. What is the main advantage of using StringBuilder over regular string concatenation in C#?
easy
A. It modifies the string without creating new string copies, improving performance.
B. It automatically sorts the characters in the string.
C. It encrypts the string for security.
D. It converts strings to uppercase by default.

Solution

  1. Step 1: Understand string immutability in C#

    Regular strings cannot be changed once created, so concatenation creates new strings each time.
  2. Step 2: How StringBuilder works

    StringBuilder changes the text in place without making new copies, which is faster for many changes.
  3. Final Answer:

    It modifies the string without creating new string copies, improving performance. -> Option A
  4. Quick Check:

    StringBuilder avoids new copies [OK]
Hint: StringBuilder changes text without copying strings [OK]
Common Mistakes:
  • Thinking StringBuilder sorts or encrypts text
  • Believing StringBuilder changes case automatically
  • Confusing StringBuilder with regular string methods
2. Which of the following is the correct way to append text to a StringBuilder named sb?
easy
A. sb.Append("Hello");
B. sb.Add("Hello");
C. sb.Insert("Hello");
D. sb.Concat("Hello");

Solution

  1. Step 1: Recall StringBuilder methods

    Append is the method used to add text at the end of the current content.
  2. Step 2: Check method names

    Add and Concat are not valid StringBuilder methods; Insert adds text at a specific position, not at the end.
  3. Final Answer:

    sb.Append("Hello"); -> Option A
  4. Quick Check:

    Append adds text at end [OK]
Hint: Use Append() to add text at the end [OK]
Common Mistakes:
  • Using Add() which does not exist
  • Confusing Insert() with Append()
  • Trying to use Concat() on StringBuilder
3. What will be the output of the following C# code?
var sb = new System.Text.StringBuilder("Hi");
sb.Append(" there");
sb.Replace("Hi", "Hello");
sb.Remove(5, 1);
Console.WriteLine(sb.ToString());
medium
A. Hello here
B. Hello there
C. Hellothere
D. Hi there

Solution

  1. Step 1: Trace Append and Replace

    Start with "Hi", Append adds " there" -> "Hi there". Replace "Hi" with "Hello" -> "Hello there".
  2. Step 2: Apply Remove

    Remove(5,1) removes 1 character at index 5 (0-based). Index 5 is the space between "Hello" and "there", so removing it joins words -> "Hellothere".
  3. Final Answer:

    Hellothere -> Option C
  4. Quick Check:

    Remove space at index 5 = "Hellothere" [OK]
Hint: Remember Remove(index, count) deletes characters at index [OK]
Common Mistakes:
  • Forgetting zero-based index in Remove
  • Assuming Replace changes all occurrences incorrectly
  • Not converting StringBuilder to string before printing
4. Identify the error in this code snippet:
var sb = new System.Text.StringBuilder();
sb.Append("Start");
sb.Remove(10, 3);
Console.WriteLine(sb.ToString());
medium
A. ToString method is missing parentheses.
B. Append method is used incorrectly.
C. StringBuilder cannot be empty when created.
D. Remove method call will throw an ArgumentOutOfRangeException.

Solution

  1. Step 1: Check Remove parameters

    Remove(10, 3) tries to remove 3 characters starting at index 10, but current string length is 5 ("Start").
  2. Step 2: Understand exception

    Removing beyond string length causes ArgumentOutOfRangeException at runtime.
  3. Final Answer:

    Remove method call will throw an ArgumentOutOfRangeException. -> Option D
  4. Quick Check:

    Remove index out of range = Exception [OK]
Hint: Check Remove index is within current length [OK]
Common Mistakes:
  • Assuming Remove silently ignores invalid indexes
  • Thinking Append is incorrect here
  • Believing ToString needs no parentheses
5. You want to build a comma-separated list of numbers from 1 to 5 using StringBuilder. Which code snippet is the most efficient and correct?
hard
A. var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i).Append(","); } sb.Remove(sb.Length - 2, 1); Console.WriteLine(sb.ToString());
B. var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i); if(i < 5) sb.Append(","); } Console.WriteLine(sb.ToString());
C. var sb = new StringBuilder(); sb.Append("1,2,3,4,5,"); Console.WriteLine(sb.ToString());
D. var sb = new StringBuilder(); for(int i=1; i<=5; i++) { sb.Append(i + ","); } Console.WriteLine(sb.ToString());

Solution

  1. Step 1: Appending comma after each number then removing trailing

    Appends number and comma each time, then removes last comma. Remove call adds overhead.
  2. Step 2: Conditional comma append

    Appends number, then comma only if not last number. Avoids extra Remove call, more efficient and clear.
  3. Step 3: Analyze options B and C

    B appends comma after last number, no removal, so extra comma remains. C hardcodes string, no loop, less flexible.
  4. Final Answer:

    sb.Append(i); if(i < 5) sb.Append(","); -> Option B
  5. Quick Check:

    Append comma conditionally [OK]
Hint: Add comma only between items, not after last [OK]
Common Mistakes:
  • Leaving trailing comma without removal
  • Hardcoding string instead of looping
  • Removing characters unnecessarily