Lesson 4 of 24
In progress
Strings and text handling
Interpolate, split, join and compare text, use StringBuilder in loops, and know how verbatim and raw strings differ.
Strings in C# are immutable, which explains most of the API: every method that changes text returns a new string, and building text in a loop allocates at every step.
What you will learn
- Use interpolation, verbatim and raw string literals.
- Split, join, trim and compare without surprises.
- Build text efficiently and format numbers.
Literals
string plain = "line onenline two";
string verbatim = @"C:dataorders.csv";
string raw = """
{
"name": "Ana",
"city": "Pune"
}
""";
A verbatim string with @ treats backslashes literally and allows newlines, which is why it is the form for file paths and regular expressions. To include a double quote inside, double it: @"He said ""hi""".
Raw string literals with three quotes need no escaping at all, which makes them the best choice for JSON and SQL. Indentation is stripped relative to the closing quotes.
Interpolation combines with both: $@"..." or $"""...""" for raw.
Common methods
string text = " Ana Rao ";
Console.WriteLine(text.Trim()); // Ana Rao
Console.WriteLine(text.Trim().Length); // 7
Console.WriteLine(text.Contains("Rao")); // true
Console.WriteLine(text.Replace("Ana", "Ananya"));
Console.WriteLine(text.ToUpperInvariant());
Console.WriteLine(text.Substring(2, 3)); // Ana
Trim, TrimStart and TrimEnd remove whitespace. ToUpperInvariant avoids the Turkish-I problem that ToUpper has under some cultures, which matters when comparing identifiers.
Substring(start, length) throws if the range is out of bounds. Modern code often uses ranges instead:
string csv = "pen,book,lamp";
Console.WriteLine(csv[..3]); // pen
Console.WriteLine(csv[^4..]); // lamp
[..3] is the first three characters; [^4..] is the last four. Range syntax works on strings, arrays and spans, and it never surprises with an off-by-one.
Split and join
string[] parts = csv.Split(',');
string joined = string.Join(" | ", parts);
string[] words = "a b c".Split(' ', StringSplitOptions.RemoveEmptyEntries);
Split(char) is simple and fast. Use the overload with StringSplitOptions to drop empty entries, which handles repeated separators.
For a pattern, Split takes a string[] of separators or a Regex. Splitting on a multi-character separator requires the string overload: Split("::").
Comparison
string a = "Ana";
string b = "ana";
Console.WriteLine(a == b); // false
Console.WriteLine(string.Equals(a, b, StringComparison.OrdinalIgnoreCase)); // true
Console.WriteLine(string.Compare(a, b, StringComparison.Ordinal)); // -1
== compares content for strings, which differs from Java and is usually what you want. For anything where case or culture matters, pass a StringComparison explicitly; the default is ordinal, which compares code units and is correct for identifiers and keys.
string.Compare with an ordinal comparison returns a negative, zero or positive number, which is the shape Sort and OrderBy expect.
Building text
var sb = new System.Text.StringBuilder();
for (int i = 1; i <= 3; i++)
{
sb.Append("item ").Append(i).AppendLine();
}
string result = sb.ToString();
StringBuilder.Append mutates the buffer, so a loop stays linear. Concatenation with + in a loop creates a new string per iteration, which becomes quadratic as the text grows.
string.Join covers the common case of gluing a collection with a separator, and interpolation covers a fixed template. Reach for StringBuilder when the number of pieces is not known in advance.
Formatting
decimal price = 1299.5m;
Console.WriteLine($"{price:F2}"); // 1299.50
Console.WriteLine($"{price:C}"); // currency for the current culture
Console.WriteLine($"{1234567:N0}"); // 1,234,567
Console.WriteLine($"{0.256:P1}"); // 25.6%
Format specifiers after a colon control the output. F2 is fixed decimals, N0 is grouped digits without decimals, P1 is a percentage with one decimal.
Culture still applies. For a CSV or an API, format with CultureInfo.InvariantCulture so the decimal separator is always a dot.
A StringBuilder also has a capacity that grows as needed. Passing an initial capacity avoids a few reallocations when the final size is known; for ordinary code the default is fine and readability matters more than the allocation.
Empty, null and whitespace
string? maybe = null;
Console.WriteLine(string.IsNullOrEmpty(maybe)); // true
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // true
Console.WriteLine(maybe?.Length ?? 0); // 0
IsNullOrWhiteSpace is the right check for user input, because a field of spaces is empty for every practical purpose. The null-conditional ?. and the null-coalescing ?? let you read from a possibly-null string without a branch.
Interpolation and culture
using System.Globalization;
string line = string.Create(CultureInfo.InvariantCulture, $"{price:F2},{qty}");
That overload formats with the given culture, which is the clean way to build machine-readable text. Without it, a machine with a comma decimal separator produces a CSV that splits into the wrong columns.
Building a CSV with interpolation and no culture, so a decimal comma adds an extra column on some machines. Use CultureInfo.InvariantCulture for anything a program will parse.
Take a full name, print it as Last, First, count the letters excluding spaces, and show whether it contains a middle name (more than two words).
Show solution
string full = " Ana Maria Rao ".Trim(); string[] parts = full.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2) { Console.WriteLine("Need at least two names."); return; } string last = parts[^1]; string first = string.Join(' ', parts[..^1]); Console.WriteLine($"{last}, {first}"); Console.WriteLine($"letters: {full.Replace(" ", "").Length}"); Console.WriteLine($"middle name: {parts.Length > 2}"); [^1] takes the last element and [..^1] everything before it, which handles middle names without a fixed format. RemoveEmptyEntries makes double spaces harmless, and Replace counts letters while ignoring spaces.
Recap
- Use
@for paths and regexes, raw strings for JSON and SQL. ==compares content; pass aStringComparisonwhen case or culture matters.StringBuilderfor loops,string.Joinfor separators, invariant culture for machine output.
Next, operators and expressions, including the null operators that make C# code compact.
Is string concatenation with + slow?
Progress is saved in this browser only. No account, no email.