C#:C# String Methods, String Interpolation, and StringBuilder
C#•Strings

C# String Methods, String Interpolation, and StringBuilder

Learn string methods (Split, Substring, Replace), immutability, and mutable StringBuilder.

Syntax

string s = "Hello"; var sb = new System.Text.StringBuilder();

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
StringBuilderClassMutable string buffer in System.Text.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C# locally:

using System;
using System.Text;

public class Program {
    public static void Main() {
        string rawEmail = "   [email protected]   ";
        string clean = rawEmail.Trim();

        Console.WriteLine($"Clean Email: {clean}");
        string[] parts = clean.Split('@');
        Console.WriteLine($"Username:    {parts[0]}");
        Console.WriteLine($"Domain:      {parts[1]}");

        // StringBuilder for high-performance concatenation
        var sb = new StringBuilder();
        for (int i = 1; i <= 3; i++) {
            sb.Append($"Node-{i} ");
        }
        Console.WriteLine($"Cluster:     {sb.ToString().Trim()}");
    }
}
Expected Output:
Clean Email: [email protected]
Username:    developer
Domain:      compilra.dev
Cluster:     Node-1 Node-2 Node-3

How It Works: Step-by-Step

  • Lines 6-11: Trim() cleans whitespace and Split() divides string into tokens.
  • Lines 14-18: StringBuilder efficiently builds concatenated string in a loop.

Key Concepts

  • C# strings are immutable; methods return new string instances.
  • StringBuilder avoids intermediate string object allocations inside loops.

Common Mistake: Concatenating strings with + in large loops

Repeated + creates a new heap string and triggers frequent garbage collection.

❌ Incorrect
string s = ""; for (int i=0; i<1000; i++) s += i;
✅ Correct
var sb = new StringBuilder(); for (int i=0; i<1000; i++) sb.Append(i);

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler