String and StringBuilder
Short, interview-ready summary of string APIs and when to use StringBuilder.
Memory hook
"string = immutable; many operations return new string; StringBuilder = mutable buffer for many concatenations"
string (immutable)
- Immutable — every “change” creates a new string
- Literal:
"hello"; Verbatim:@"C:\path"(no escape except""→") - Interpolation:
$"Name: {name}"
Common string APIs
Length and indexing
int len = s.Length;
char c = s[0];
Comparison
bool eq = s1 == s2;
int cmp = string.Compare(s1, s2, StringComparison.Ordinal); // <0, 0, >0
bool eqIgnoreCase = s1.Equals(s2, StringComparison.OrdinalIgnoreCase);
- Prefer StringComparison.Ordinal (or OrdinalIgnoreCase) for performance and clarity unless you need culture-specific rules
Search and substring
bool has = s.Contains("ab");
int idx = s.IndexOf("ab"); // -1 if not found
int last = s.LastIndexOf("ab");
bool starts = s.StartsWith("ab");
bool ends = s.EndsWith("xy");
string sub = s.Substring(2, 3); // start, length
string sub2 = s[2..5]; // range (C# 8+)
Modify (return new string)
string lower = s.ToLower();
string upper = s.ToUpper();
string trimmed = s.Trim(); // TrimStart, TrimEnd
string replaced = s.Replace("a", "b");
string removed = s.Remove(2, 3); // start, count
string inserted = s.Insert(2, "xy");
Split and join
string[] parts = s.Split(',');
string[] parts2 = s.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
string joined = string.Join(", ", items);
Formatting
string formatted = string.Format("{0} is {1}", name, age);
string interpolated = $"{name} is {age}";
Null/empty check
bool empty = string.IsNullOrEmpty(s);
bool white = string.IsNullOrWhiteSpace(s);
StringBuilder (mutable, many concatenations)
"Use when building a string in a loop or with many concatenations"
var sb = new StringBuilder();
sb.Append("Hello");
sb.AppendLine(" World");
sb.AppendFormat("{0}", value);
sb.AppendJoin(", ", items);
sb.Insert(0, "Prefix ");
sb.Remove(0, 3);
sb.Replace("a", "b");
sb.Clear();
string result = sb.ToString();
int len = sb.Length;
sb.Length = 0; // clear without new allocation
- Append / AppendLine — add to end
- ToString() — build final string
- Avoid string + string in loops; use StringBuilder instead
"string is immutable; operations like Replace or Trim return a new string. Use common APIs for comparison (Ordinal), search (IndexOf, Contains), split/join, and null checks. Use StringBuilder when building a string with many concatenations to avoid allocations."
Cheat sheet
string = immutable; literal "", verbatim @", interpolated $
Contains, IndexOf, StartsWith, EndsWith
Substring, Replace, Trim, Split, Join
string.IsNullOrEmpty, IsNullOrWhiteSpace
StringBuilder = Append, AppendLine, ToString(); use in loops