Text formatting and parsing appear in almost every program, from logs to APIs.
A string is an immutable sequence of UTF-16 characters. Methods like ToUpper, Replace or Trim return a new string; the original never changes.
Interpolated strings put expressions inside {}: $"Total: {total:C2}". After a colon comes a format string (N2 for two decimals with separators, C for currency, yyyy-MM-dd for dates); after a comma comes alignment ({name,-10} pads to 10 characters, left-aligned).
Other literal forms:
- Verbatim
@"C:\temp\new"treats backslashes literally and allows line breaks. - Raw string literals start and end with at least three quotes,
"""...""", and can contain quotes and backslashes unescaped; ideal for JSON or SQL. Combine with$for interpolation.
Useful members: Length, Contains, StartsWith, IndexOf, Substring, Split, string.Join, string.IsNullOrWhiteSpace. Indexes and ranges work too: s[^1] is the last char, s[..3] the first three.
Compare strings with ==, which compares content (unlike Java). For case-insensitive comparison use string.Equals(a, b, StringComparison.OrdinalIgnoreCase) rather than lower-casing both.
Because strings are immutable, concatenating in a loop creates many temporary strings. Use StringBuilder (in System.Text) to build large text incrementally, then call ToString() once.
Example
using System.Text;
string name = "Ada";
decimal total = 1234.5m;
Console.WriteLine($"{name,-5}|{total:N2}"); // Ada |1,234.50
Console.WriteLine(@"C:\temp\new"); // C:\temp\new (verbatim)
string json = $$"""{"user": "{{name}}"}""";
Console.WriteLine(json); // {"user": "Ada"}
string s = " Hello, World ".Trim();
Console.WriteLine(s[..5]); // Hello
Console.WriteLine(s[^1]); // d
Console.WriteLine(string.Join("-", s.Split(", "))); // Hello-World
Console.WriteLine("abc" == new string(['a', 'b', 'c'])); // True
var sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.Append(i).Append(';');
Console.WriteLine(sb.ToString()); // 0;1;2;Remember
- Strings are immutable; methods return new strings
- $"{expr:format}" interpolates with optional formatting
- == compares string contents
- Use StringBuilder for building text in loops
Watch out for
- Calling s.Replace("a", "b") and ignoring the returned string.