06
Lesson 6 of 35 · Foundations

String Manipulation

Strings are one of the most-used types in C#. This lesson covers string literals, escape sequences, interpolation, verbatim strings, the most useful String methods, and the efficient StringBuilder class.

String Literals & Escape Sequences

A string literal is text enclosed in double quotes. Use backslash escape sequences for special characters: \n (newline), \t (tab), \\ (backslash), \" (double quote). A verbatim string prefixed with @ treats every character literally—useful for file paths.

Literals Literals.cs
string path    = "C:\\Users\\Alice\\docs";  // escaped
string vPath   = @"C:\Users\Alice\docs";   // verbatim — same result
string multiline = @"Line 1
Line 2
Line 3";
string tab     = "Column1\tColumn2";

String Interpolation

Prefix a string with $ to embed expressions directly inside curly braces. Format specifiers can follow a colon: {price:C2} formats as currency with 2 decimal places. Combine $ and @ as $@ for verbatim interpolated strings.

Interpolation Interpolation.cs
string first = "Alice", last = "Smith";
int age = 28;
double salary = 75000.5;

Console.WriteLine($"Name: {first} {last}, Age: {age}");
Console.WriteLine($"Salary: {salary:C2}");
Console.WriteLine($"Upper: {first.ToUpper()}");
Console.WriteLine($@"Path: C:\Users\{first}\docs");

Common String Methods

The String class provides dozens of useful methods. The most important ones include Length, ToUpper()/ToLower(), Trim(), Contains(), StartsWith()/EndsWith(), Replace(), Split(), Substring(), and IndexOf().

String methods StringMethods.cs
string s = "  Hello, World!  ";
Console.WriteLine(s.Trim());             // "Hello, World!"
Console.WriteLine(s.Trim().ToUpper());   // "HELLO, WORLD!"
Console.WriteLine(s.Contains("World")); // True
Console.WriteLine(s.Replace("World", "C#")); // "  Hello, C#!  "

string csv = "apple,banana,cherry";
string[] fruits = csv.Split(',');
foreach (string f in fruits)
    Console.WriteLine(f);

string sub = "Hello World";
Console.WriteLine(sub.Substring(6, 5));  // "World"
Console.WriteLine(sub[6..]);             // "World" (C# range syntax)

StringBuilder for Performance

Every time you concatenate strings with +, a new string object is created. For building large strings in a loop, use StringBuilder from System.Text—it mutates a single buffer internally, making it much faster.

StringBuilder SB.cs
using System.Text;

var sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
    sb.AppendLine($"Line {i}: {i * i}");

string result = sb.ToString();
Console.Write(result);