Skip to Content
Course content

115: String Methods and StringBuilder

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this all the time when I'm reviewing junior code: a for loop that builds a large string using the += operator. It looks clean, it's intuitive, and it works perfectly fine when you're only dealing with five or ten items. The misconception is that C# is "smart enough" to just append the new text to the existing memory location of that string.

The Myth that += is Just a Shortcut

It isn't. In C#, strings are immutable. When you write myString += " next part";, you aren't actually adding text to the end of the original string. Instead, the runtime creates a brand new string object in memory, copies the old content over, appends the new content, and then throws the old string away for the Garbage Collector to clean up.

// This is a performance disaster in a real application
string report = "";
for (int i = 0; i < 10000; i++) 
{
    // Every single iteration creates a whole new string object
    report += $"Line {i}: System status OK\n"; 
}

If you do this with 10,000 iterations, you've just created 10,000 string objects. Most of them are garbage immediately after they are created. On a small scale, you won't notice. In a high-traffic production environment, this is how you create memory pressure and trigger massive GC pauses that make your app stutter.

The Power of the Mutable Buffer

This is exactly why StringBuilder exists. Think of it as a dynamic buffer—a workspace where you can throw text, chop it up, and append to it without constantly allocating new memory. It only creates the final string once, at the very end, when you call ToString().

using System.Text;

var logBuilder = new StringBuilder();
for (int i = 0; i < 10000; i++) 
{
    // This modifies the internal buffer rather than creating a new object
    logBuilder.AppendLine($"Line {i}: System status OK");
}

string finalReport = logBuilder.ToString();

I generally follow this rule of thumb: if you're concatenating more than three or four strings, or if you're doing it inside any kind of loop, reach for the StringBuilder. Your memory profiler will thank you.

Cleaning Up the Mess with String Methods

While StringBuilder is for building, the String class provides a massive library of methods for manipulating existing text. You'll find yourself using these constantly to sanitize user input or parse data.

Take a look at these common heavy-hitters:

  • Trim(), TrimStart(), TrimEnd(): Essential for removing accidental whitespace from the ends of a string.
  • Replace("old", "new"): Great for swapping placeholders or cleaning up forbidden characters.
  • Split('delimiter'): Turns a single string into an array. Be careful here; splitting a massive string can create a lot of small string objects.
  • Substring(startIndex, length): Grabs a specific chunk of a string. Just remember that it throws an exception if you try to grab more characters than the string actually contains.
string rawInput = "  ERROR: Database Timeout [Code: 404]  ";

// Clean up the edges
string cleanInput = rawInput.Trim(); 

// Isolate the error code
// We find the index of the bracket and slice from there
int start = cleanInput.IndexOf("[") + 1;
int length = cleanInput.IndexOf("]") - start;
string errorCode = cleanInput.Substring(start, length);

Console.WriteLine($"Cleaned Error: {errorCode}"); // Output: Code: 404

One quick tip: Always check for null or use the null-conditional operator before calling these methods. There is nothing more annoying than a NullReferenceException because a user left a text field empty.




📋 Practical Task

Build a CSV-to-Summary Log Generator

You have been given a raw string containing several rows of comma-separated values (CSV). Each row represents a system event: Timestamp, Level, Message. However, the raw data is "dirty"—it has leading/trailing whitespace and inconsistent casing.

Your Task: Write a program that parses this raw string and uses a StringBuilder to create a formatted summary report.

Requirements:

  • Input string: " 2023-10-01, info, System Started \n 2023-10-01, warn, Low Disk Space \n 2023-10-02, error, Connection Failed "
  • For each line:
    1. Split the line by the comma.
    2. Trim the whitespace from each piece.
    3. Ensure the "Level" (info, warn, error) is converted to UPPERCASE.
    4. Append it to a StringBuilder in the format: [LEVEL] Date: Message
  • Output the final resulting string to the console.

Expected Output:
[INFO] 2023-10-01: System Started
[WARN] 2023-10-01: Low Disk Space
[ERROR] 2023-10-02: Connection Failed

Rating
0 0

There are no comments for now.

to be the first to leave a comment.