7. Strings
A string is an immutable sequence of characters: every operation returns a new string instead of changing the old one. Strings are reference types but compare by content with ==. Characters are accessed by index (s[0]) and the first index is 0, so the last one is s[s.Length - 1] (or s[^1]). You can slice with ranges (s[2..5]). A char is a single character written with single quotes ('A') and a string uses double quotes ("A").
Common members: Length, ToUpper, ToLower, Trim (TrimStart, TrimEnd), Substring, IndexOf, LastIndexOf, Contains, StartsWith, EndsWith, Replace, Insert, Remove, PadLeft, PadRight, Split, Join, Concat, Equals, Compare, and the static helpers string.IsNullOrEmpty and string.IsNullOrWhiteSpace. Use string interpolation ($"...{value}...") to embed values and format specifiers such as {price:F2} (fixed decimals), {n:D5} (pad with zeros), {n:X} (hexadecimal) and {n,8} (align in a width). Escape sequences (\n new line, \t tab, \" quote, \\ backslash) go inside normal strings; verbatim strings (@"C:\path") ignore backslashes and raw string literals ("""...""") allow quotes and multiple lines without escaping.
For building long strings in loops use StringBuilder, because repeated + creates many temporary strings. The char type has helpers such as char.IsDigit, char.IsLetter, char.IsUpper and char.ToUpper. Dates are formatted with custom patterns on DateTime ("yyyy-MM-dd").
- Common string operations
- Indexing, slicing and searching
- Checking content
- Comparing strings
- Changing text creates a new string
- Split and Join
- Formatting with interpolation
- Escape sequences, verbatim and raw strings
- StringBuilder
- Characters, reversing and palindromes
- Counting words and vowels
- Dates and formatting
Key points to remember
- Strings are immutable: s.ToUpper() alone does nothing useful; assign the result (s = s.ToUpper()).
- Compare text with == or string.Equals. For case-insensitive comparison use StringComparison.OrdinalIgnoreCase rather than ToLower() on both sides.
- Use string.IsNullOrWhiteSpace(s) to check user input: it catches null, empty and spaces-only values.
- Substring(start, length) takes a length; the range s[start..end] takes an end index that is not included.
- Substring, Remove and Insert throw ArgumentOutOfRangeException when an index is outside the string; check Length first.
- Split can remove empty pieces: Split(' ', StringSplitOptions.RemoveEmptyEntries).
- Use StringBuilder when joining many pieces; use string.Join for a collection.
- Format specifiers such as C (currency), N (thousands separators) and P (percent) follow the computer's culture. Use CultureInfo.InvariantCulture when output must be identical everywhere.
- Never build SQL or file paths by joining user text; use parameters and Path.Combine.
Example 1: Common string operations
string s = " Hello C# ";
string t = s.Trim();
Console.WriteLine(t.Length);
Console.WriteLine(t.ToUpper());
Console.WriteLine(t.Contains("C#"));
Console.WriteLine(t.Replace("Hello", "Hi"));
Console.WriteLine(string.Join("-", "a,b,c".Split(',')));
Show output
Output8 HELLO C# True Hi C# a-b-c
Example 2: Indexing, slicing and searching
string s = "Programming";
Console.WriteLine(s[0]);
Console.WriteLine(s[^1]); // last character
Console.WriteLine(s.Substring(3, 4)); // start 3, length 4
Console.WriteLine(s[..3]); // first three
Console.WriteLine(s[^3..]); // last three
Console.WriteLine(s.IndexOf('g'));
Console.WriteLine(s.LastIndexOf('g'));
Console.WriteLine(s.IndexOf("xyz")); // -1 means not found
Show output
OutputP g gram Pro ing 3 10 -1
Example 3: Checking content
string file = "report_2025.pdf";
Console.WriteLine(file.StartsWith("report"));
Console.WriteLine(file.EndsWith(".pdf"));
Console.WriteLine(file.Contains("2025"));
Console.WriteLine(file.IndexOf("_"));
Console.WriteLine(string.IsNullOrEmpty(""));
Console.WriteLine(string.IsNullOrWhiteSpace(" "));
Console.WriteLine(char.IsDigit(file[7]));
Show output
OutputTrue True True 6 True True True
Example 4: Comparing strings
string a = "apple", b = "APPLE";
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase));
Console.WriteLine(string.Compare("apple", "banana") < 0); // apple sorts first
Console.WriteLine("b".CompareTo("a") > 0);
Show output
OutputFalse True True True
Example 5: Changing text creates a new string
string s = "Hello"; Console.WriteLine(s.Insert(5, " World")); Console.WriteLine(s.Remove(1, 3)); Console.WriteLine(s.PadLeft(8, '*')); Console.WriteLine(s.PadRight(8, '-') + "|"); Console.WriteLine(s.ToLower()); Console.WriteLine(s); // the original never changed
Show output
OutputHello World Ho ***Hello Hello---| hello Hello
Example 6: Split and Join
string csv = "Ann,30,Cape Town";
string[] parts = csv.Split(',');
Console.WriteLine(parts.Length);
Console.WriteLine(parts[2]);
string sentence = "one two three";
Console.WriteLine(sentence.Split(' ').Length); // empty piece included
Console.WriteLine(sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length);
Console.WriteLine(string.Join(" | ", parts));
Console.WriteLine(string.Concat("a", "b", "c"));
Show output
Output3 Cape Town 4 3 Ann | 30 | Cape Town abc
Example 7: Formatting with interpolation
double price = 1234.5;
int n = 42;
Console.WriteLine($"{price:F2}"); // fixed, 2 decimals
Console.WriteLine($"{n:D5}"); // pad with zeros
Console.WriteLine($"{255:X}"); // hexadecimal
Console.WriteLine($"[{n,6}]"); // right-aligned in 6 characters
Console.WriteLine($"[{n,-6}]"); // left-aligned
Console.WriteLine(string.Format("{0} has {1} items", "Cart", 3));
Console.WriteLine($"{(n > 40 ? "big" : "small")}"); // expression in braces
Show output
Output1234.50 00042 FF [ 42] [42 ] Cart has 3 items big
Example 8: Escape sequences, verbatim and raw strings
Console.WriteLine("Line1\nLine2");
Console.WriteLine("Tab\there");
Console.WriteLine("She said \"hi\"");
Console.WriteLine("Backslash: \\");
Console.WriteLine(@"C:\Users\Ann\file.txt");
string json = """
{"name": "Ann", "age": 30}
"""; // raw string literal (C# 11)
Console.WriteLine(json);
Show output
OutputLine1
Line2
Tab here
She said "hi"
Backslash: \
C:\Users\Ann\file.txt
{"name": "Ann", "age": 30}
Example 9: StringBuilder
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.Append(i).Append(' ');
Console.WriteLine(sb.ToString().Trim());
var report = new StringBuilder();
report.Append("Hello");
report.Append(' ');
report.AppendLine("World");
report.Insert(0, ">> ");
report.Replace("World", "C#");
Console.WriteLine(report.ToString().TrimEnd());
Show output
Output0 1 2 >> Hello C#
Example 10: Characters, reversing and palindromes
string word = "Level";
char[] chars = word.ToLower().ToCharArray();
Array.Reverse(chars);
string reversed = new string(chars);
Console.WriteLine(reversed);
Console.WriteLine(word.ToLower() == reversed); // palindrome check
Console.WriteLine(char.IsDigit('7'));
Console.WriteLine(char.IsLetter('7'));
Console.WriteLine(char.ToUpper('a'));
Console.WriteLine((int)'A'); // character code
Console.WriteLine((char)('A' + 2));
Show output
Outputlevel True True False A 65 C
Example 11: Counting words and vowels
string text = "the quick brown fox";
int words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
int vowels = text.Count(c => "aeiou".Contains(c));
Console.WriteLine(words);
Console.WriteLine(vowels);
string title = string.Join(" ", text.Split(' ')
.Select(w => char.ToUpper(w[0]) + w.Substring(1)));
Console.WriteLine(title);
Show output
Output4 5 The Quick Brown Fox
Example 12: Dates and formatting
var date = new DateTime(2025, 3, 7);
Console.WriteLine(date.ToString("yyyy-MM-dd"));
Console.WriteLine(date.ToString("dd MMM yyyy"));
Console.WriteLine(date.DayOfWeek);
Console.WriteLine(date.AddDays(30).ToString("yyyy-MM-dd"));
TimeSpan gap = new DateTime(2025, 3, 10) - date;
Console.WriteLine(gap.Days);
Console.WriteLine(DateTime.TryParse("2025-12-25", out DateTime xmas));
Console.WriteLine(xmas.Month);
Show output
Output2025-03-07 07 Mar 2025 Friday 2025-04-06 3 True 12