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:
| Parameter | Type | Description |
|---|---|---|
| StringBuilder | Class | Mutable string buffer in System.Text. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C# List<T> and LINQ Queries: Where, Select, and Aggregate
Master dynamic List<T> collections and powerful LINQ queries (Where, Select, Sum).
C# Console Input and Output: Console.WriteLine and ReadLine
Print formatted output and read user inputs from standard console streams.
C# Strongly Typed Implicit Var Assignments and Data Types
Master C# static typing with implicit var inference, primitive types (int, double, decimal, bool), and formatting specifiers.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.