Strings & StringBuilder
Strings are sequences of characters. C# provides powerful tools for string manipulation, comparison, and formatting.
1. String Manipulation
Strings are immutable in C# (cannot be changed once created).
2. Common String Methods
| MethodDescriptionExample | ||
Length | Returns length of string | "Hello".Length → 5 |
Substring(start, len) | Extracts substring | "Hello".Substring(1, 3) → "ell" |
IndexOf(char/string) | Finds index of first occurrence | "Hello".IndexOf('l') → 2 |
LastIndexOf(char) | Finds index of last occurrence | "Hello".LastIndexOf('l') → 3 |
Replace(old, new) | Replaces characters or words | "Hello".Replace('l','x') → "Hexxo" |
Contains(value) | Checks if string contains value | "Hello".Contains("ll") → true |
StartsWith(value) | Checks start of string | "Hello".StartsWith("He") → true |
EndsWith(value) | Checks end of string | "Hello".EndsWith("lo") → true |
Split(separator) | Splits string into array | "a,b,c".Split(',') → ["a","b","c"] |
Insert(index, string) | Inserts string at specified index | "Hello".Insert(1,"123") → "H123ello" |
Remove(start, count) | Removes characters | "Hello".Remove(1,3) → "Ho" |
Example:
3. String Interpolation
Easier way to combine strings with variables using $.
Alternative:
4. StringBuilder Class
StringBuilder is mutable and efficient for multiple modifications.
Common Methods of StringBuilder:
Append()→ Add text at endInsert(index, string)→ Insert text at indexRemove(start, length)→ Remove part of stringReplace(old, new)→ Replace substringClear()→ Remove all content
5. Comparing Strings
Strings can be compared using ==, Equals(), or CompareTo().
Explanation:
==→ Compares valuesEquals()→ Can ignore caseCompareTo()→ Returns integer:- 0 → equal
- <0 → s1 < s2
0 → s1 > s2
6. Formatting Strings
C# provides multiple ways to format strings.
6.1 Composite Formatting
6.2 String Interpolation
6.3 String.Format
6.4 Padding & Alignment
Summary of Chapter 7:
- Strings are immutable;
StringBuilderis mutable. - String methods help manipulation, searching, and slicing.
- String interpolation and formatting simplify output.
- String comparison can be case-sensitive or insensitive.
StringBuilderis efficient for frequent modifications.