iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Strings

C# strings are immutable. Build them with interpolation ($"…"), verbatim literals (@"…"), or raw string literals ("""…""" in C# 11+).

Three literals + common APIs

EXAMPLE
var name = "Ada";
var age  = 36;

// 1) Interpolation
var a = $"Hello, {name} — you are {age:00} years old";

// 2) Verbatim — \\ is literal, embedded newlines preserved
var path = @"C:\Users\ada\src";
var json = @"{
    ""name"": ""Ada""
}";

// 3) Raw string literals (C# 11+) — no escaping needed
var json2 = """
{
    "name": "Ada",
    "age": 36
}
""";

// Common ops
name.Length;
name.ToUpperInvariant();
name.Trim();
name.IndexOf('d');
name.Contains("da");
name.StartsWith("A");

// Compare — culture-invariant by default for code paths
name.Equals("Ada", StringComparison.Ordinal);
string.Equals(name, "ADA", StringComparison.OrdinalIgnoreCase);

// Replace + split
"a,b,c".Split(',');
"hello".Replace("l", "L");
Regex.Replace("hello world", @"\s+", "-");

// Hot-loop edits — StringBuilder
var sb = new StringBuilder();
for (var i = 0; i < 1000; i++) sb.Append(i).Append(',');
var bigString = sb.ToString();

// Format string
var formatted = string.Format("{0} scored {1:N0}", name, 12345);

// Span<char> — zero-allocation slicing (hot paths)
ReadOnlySpan<char> span = name.AsSpan(0, 2);   // "Ad"

Why it matters

StringComparison.Ordinal is what most code paths want. The default culture-aware comparison is slow AND produces locale-dependent results — not what you want comparing tokens or paths.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
string s = "Hello";
Console.WriteLine(s.Length);
Console.WriteLine(s.ToUpper());
Console.WriteLine(\$"Greeting: {s}, {DateTime.Now:yyyy}");
Try it Yourself »

Discussion

Loading…