12. Strings & Text
Names, emails, URLs, JSON: most data a backend touches is text. A string is a sequence of characters, and the string type comes with dozens of methods to search, slice, and reshape it.
Strings are immutable
Once created, a string never changes. Methods like ToUpper return a new string and leave the original alone. Forgetting to use the result is a common beginner bug.
string name = "ada";
name.ToUpper();
Console.WriteLine(name);
name = name.ToUpper();
Console.WriteLine(name);ada ADA
Common methods
These cover most everyday work. Indexes start at 0, and IndexOf returns -1 when nothing is found. Comparisons are case-sensitive unless you pass a StringComparison.
string title = " Learn C# in Y Minutes ";
string clean = title.Trim();
Console.WriteLine($"[{clean}]");
Console.WriteLine(clean.ToUpper());
Console.WriteLine(clean.ToLower());
Console.WriteLine($"Length: {clean.Length}");
Console.WriteLine($"Index of 'C#': {clean.IndexOf("C#")}");
Console.WriteLine($"Substring(6, 2): {clean.Substring(6, 2)}");
Console.WriteLine($"Range [..5]: {clean[..5]}");
Console.WriteLine(clean.Replace("Y", "10"));
Console.WriteLine($"Contains 'Minutes'? {clean.Contains("Minutes")}");
Console.WriteLine($"StartsWith 'learn' (ignore case)? {clean.StartsWith("learn", StringComparison.OrdinalIgnoreCase)}");
Console.WriteLine($"Blank? {string.IsNullOrWhiteSpace(" ")}");[Learn C# in Y Minutes] LEARN C# IN Y MINUTES learn c# in y minutes Length: 21 Index of 'C#': 6 Substring(6, 2): C# Range [..5]: Learn Learn C# in 10 Minutes Contains 'Minutes'? True StartsWith 'learn' (ignore case)? True Blank? True
Check user input with string.IsNullOrWhiteSpace. It catches null, "", and " " in one call.
Split and Join
Split breaks a string into an array at a separator. string.Join glues an array back together. The options RemoveEmptyEntries and TrimEntries clean up messy input like extra commas and spaces.
string fullName = "Ada Lovelace";
string[] parts = fullName.Split(' ');
Console.WriteLine($"First: {parts[0]}, Last: {parts[1]}");
string csv = "apple, banana,,cherry ";
string[] fruits = csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Console.WriteLine($"{fruits.Length} fruits");
Console.WriteLine(string.Join(" + ", fruits));First: Ada, Last: Lovelace 3 fruits apple + banana + cherry
Formatting numbers
Inside interpolation, add a format specifier after a colon: F2 two decimals, N0 thousands separators, P1 percent, D5 pad with zeros. A number after a comma sets the width: negative aligns left, positive aligns right.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
double pi = Math.PI;
int visitors = 1234567;
decimal price = 19.5m;
double rate = 0.256;
Console.WriteLine($"Pi: {pi:F2}");
Console.WriteLine($"Visitors: {visitors:N0}");
Console.WriteLine($"Price: {price:F2}");
Console.WriteLine($"Rate: {rate:P1}");
Console.WriteLine($"Order: {42:D5}");
Console.WriteLine($"|{"Item",-8}|{"Qty",5}|");
Console.WriteLine($"|{"Apple",-8}|{3,5}|");Pi: 3.14 Visitors: 1,234,567 Price: 19.50 Rate: 25.6 % Order: 00042 |Item | Qty| |Apple | 3|
Escapes, verbatim, and raw strings
- Escape sequences start with a backslash:
\nnew line,\ttab,\"quote,\\backslash. - A verbatim string
@"..."ignores escapes. Handy for Windows paths. - A raw string literal
"""..."""keeps everything as written, quotes included. Perfect for JSON. The indentation of the closing quotes is removed from every line. Add$$to interpolate with{{double braces}}, so single braces stay plain JSON.
Console.WriteLine("Line one\nLine two");
Console.WriteLine("Name:\tAda");
Console.WriteLine("She said \"hi\"");
string path = @"C:\Users\ada\notes.txt";
Console.WriteLine(path);
string json = """
{
"name": "Ada",
"role": "admin"
}
""";
Console.WriteLine(json);
string user = "Linus";
string body = $$"""
{ "name": "{{user}}" }
""";
Console.WriteLine(body);Line one
Line two
Name: Ada
She said "hi"
C:\Users\ada\notes.txt
{
"name": "Ada",
"role": "admin"
}
{ "name": "Linus" }StringBuilder
Because strings are immutable, building one with += in a loop creates a new string on every pass. A StringBuilder is a mutable buffer: append as much as you like, then call ToString once at the end. Reach for it when you build text in a loop.
using System.Text;
var sb = new StringBuilder();
sb.AppendLine("Receipt");
sb.AppendLine(new string('-', 12));
string[] items = ["Coffee", "Bagel", "Juice"];
foreach (var item in items)
{
sb.Append("* ").AppendLine(item);
}
sb.Replace("*", "-");
sb.Insert(0, "== ");
Console.Write(sb.ToString());== Receipt ------------ - Coffee - Bagel - Juice
Exercise: summarize text
Put it together: shorten a long text to a maximum length without cutting a word in half. LastIndexOf(' ', maxLength) searches backwards for the last space that fits, and the range text[..cut] keeps everything before it.
string article = "C# is a modern, object-oriented language used to build web APIs, games, and apps.";
Console.WriteLine(Summarize(article, 40));
Console.WriteLine(Summarize("Short and sweet.", 30));
static string Summarize(string text, int maxLength)
{
if (text.Length <= maxLength)
return text;
int lastSpace = text.LastIndexOf(' ', maxLength);
int cut = lastSpace > 0 ? lastSpace : maxLength;
return text[..cut].TrimEnd(',', '.') + "...";
}C# is a modern, object-oriented language... Short and sweet.
Strings arrive in every request: route values, query strings, headers. Validate and normalize them before using them:
app.MapGet("/search", (string? q) =>
{
if (string.IsNullOrWhiteSpace(q))
return Results.BadRequest("q is required");
return Results.Ok($"Searching for '{q.Trim()}'");
});