Working with Strings
Strings are one of the most commonly used data types in programming. In this lesson, you'll learn how to create and manipulate strings in C#.
What is a String?
A string is a sequence of characters enclosed in double quotes.
csharp1string greeting = "Hello, World!";2string name = "Alice";3string empty = "";
String Concatenation
Combine strings using the + operator:
csharp1string firstName = "John";2string lastName = "Doe";34// Concatenation with +5string fullName = firstName + " " + lastName;6Console.WriteLine(fullName); // John Doe78// Building a message9string message = "Hello, " + firstName + "!";10Console.WriteLine(message); // Hello, John!
String Interpolation
A cleaner way to embed values in strings using $:
csharp1string name = "Alice";2int age = 30;3double height = 1.75;45// String interpolation6Console.WriteLine($"Name: {name}");7Console.WriteLine($"Age: {age}");8Console.WriteLine($"{name} is {age} years old");910// Expressions inside braces11Console.WriteLine($"Next year, {name} will be {age + 1}");12Console.WriteLine($"Height in cm: {height * 100}");
Formatting with Interpolation
csharp1double price = 19.99;2DateTime today = DateTime.Now;34// Format numbers5Console.WriteLine($"Price: {price:C}"); // Price: $19.99 (currency)6Console.WriteLine($"Price: {price:F1}"); // Price: 20.0 (1 decimal)78// Format dates9Console.WriteLine($"Date: {today:d}"); // Short date10Console.WriteLine($"Date: {today:yyyy-MM-dd}"); // 2024-01-151112// Alignment13Console.WriteLine($"|{name,10}|"); // Right-align in 10 chars14Console.WriteLine($"|{name,-10}|"); // Left-align in 10 chars
Escape Sequences
Special characters in strings:
csharp1// Common escape sequences2Console.WriteLine("Hello\tWorld"); // Tab3Console.WriteLine("Line 1\nLine 2"); // New line4Console.WriteLine("She said \"Hi\""); // Quotes5Console.WriteLine("Path: C:\\Users"); // Backslash67// All escape sequences8// \t Tab9// \n New line10// \\ Backslash11// \" Double quote12// \' Single quote13// \r Carriage return
Verbatim Strings
Use @ for strings that should be taken literally (no escape processing):
csharp1// Without verbatim (need to escape backslashes)2string path1 = "C:\\Users\\Documents\\file.txt";34// With verbatim (no escaping needed)5string path2 = @"C:\Users\Documents\file.txt";67// Multi-line verbatim strings8string multiLine = @"This is line 19This is line 210This is line 3";1112// To include quotes in verbatim strings, double them13string quoted = @"He said ""Hello""";
Raw String Literals (C# 11+)
For complex strings with quotes and special characters:
csharp1// Raw string literal (three or more quotes)2string json = """3 {4 "name": "Alice",5 "age": 306 }7 """;89// Interpolated raw strings10string name = "Alice";11string data = $"""12 Name: {name}13 Status: Active14 """;
Common String Properties and Methods
csharp1string text = "Hello, World!";23// Properties4int length = text.Length; // 1356// Case conversion7string upper = text.ToUpper(); // HELLO, WORLD!8string lower = text.ToLower(); // hello, world!910// Searching11bool contains = text.Contains("World"); // true12int index = text.IndexOf("World"); // 713bool starts = text.StartsWith("Hello"); // true14bool ends = text.EndsWith("!"); // true1516// Extracting17string sub = text.Substring(0, 5); // Hello18char first = text[0]; // H1920// Modifying (returns new string)21string replaced = text.Replace("World", "C#"); // Hello, C#!22string trimmed = " hello ".Trim(); // hello
String Comparison
csharp1string a = "hello";2string b = "Hello";34// Case-sensitive comparison5bool equal1 = a == b; // false6bool equal2 = a.Equals(b); // false78// Case-insensitive comparison9bool equal3 = a.Equals(b, StringComparison.OrdinalIgnoreCase); // true10bool equal4 = string.Equals(a, b, StringComparison.OrdinalIgnoreCase); // true
Null and Empty Strings
csharp1string empty = "";2string nullString = null;3string whitespace = " ";45// Checking for empty or null6bool isEmpty = string.IsNullOrEmpty(empty); // true7bool isNullOrEmpty = string.IsNullOrEmpty(nullString); // true8bool hasContent = string.IsNullOrWhiteSpace(whitespace); // true910// Safe way to work with potentially null strings11string name = null;12int length = name?.Length ?? 0; // 0 (null-conditional + null-coalescing)
Building Strings Efficiently
For many concatenations, use StringBuilder:
csharp1using System.Text;23// Inefficient for many concatenations4string result = "";5for (int i = 0; i < 1000; i++)6{7 result += i + ", "; // Creates new string each time8}910// Efficient alternative11StringBuilder sb = new StringBuilder();12for (int i = 0; i < 1000; i++)13{14 sb.Append(i);15 sb.Append(", ");16}17string result = sb.ToString();
Summary
In this lesson, you learned:
- Strings are sequences of characters in double quotes
- Concatenate with
+or use interpolation with$"...{value}..." - Use escape sequences (
\n,\t,\\) for special characters - Use verbatim strings (
@"...") for paths and multi-line text - Common methods:
Length,ToUpper(),Contains(),Substring(),Replace() - Check for null/empty with
string.IsNullOrEmpty()
Next, we'll learn how to convert between different data types.