12 minlesson

Working with Strings

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.

csharp
1string greeting = "Hello, World!";
2string name = "Alice";
3string empty = "";

String Concatenation

Combine strings using the + operator:

csharp
1string firstName = "John";
2string lastName = "Doe";
3
4// Concatenation with +
5string fullName = firstName + " " + lastName;
6Console.WriteLine(fullName); // John Doe
7
8// Building a message
9string message = "Hello, " + firstName + "!";
10Console.WriteLine(message); // Hello, John!

String Interpolation

A cleaner way to embed values in strings using $:

csharp
1string name = "Alice";
2int age = 30;
3double height = 1.75;
4
5// String interpolation
6Console.WriteLine($"Name: {name}");
7Console.WriteLine($"Age: {age}");
8Console.WriteLine($"{name} is {age} years old");
9
10// Expressions inside braces
11Console.WriteLine($"Next year, {name} will be {age + 1}");
12Console.WriteLine($"Height in cm: {height * 100}");

Formatting with Interpolation

csharp
1double price = 19.99;
2DateTime today = DateTime.Now;
3
4// Format numbers
5Console.WriteLine($"Price: {price:C}"); // Price: $19.99 (currency)
6Console.WriteLine($"Price: {price:F1}"); // Price: 20.0 (1 decimal)
7
8// Format dates
9Console.WriteLine($"Date: {today:d}"); // Short date
10Console.WriteLine($"Date: {today:yyyy-MM-dd}"); // 2024-01-15
11
12// Alignment
13Console.WriteLine($"|{name,10}|"); // Right-align in 10 chars
14Console.WriteLine($"|{name,-10}|"); // Left-align in 10 chars

Escape Sequences

Special characters in strings:

csharp
1// Common escape sequences
2Console.WriteLine("Hello\tWorld"); // Tab
3Console.WriteLine("Line 1\nLine 2"); // New line
4Console.WriteLine("She said \"Hi\""); // Quotes
5Console.WriteLine("Path: C:\\Users"); // Backslash
6
7// All escape sequences
8// \t Tab
9// \n New line
10// \\ Backslash
11// \" Double quote
12// \' Single quote
13// \r Carriage return

Verbatim Strings

Use @ for strings that should be taken literally (no escape processing):

csharp
1// Without verbatim (need to escape backslashes)
2string path1 = "C:\\Users\\Documents\\file.txt";
3
4// With verbatim (no escaping needed)
5string path2 = @"C:\Users\Documents\file.txt";
6
7// Multi-line verbatim strings
8string multiLine = @"This is line 1
9This is line 2
10This is line 3";
11
12// To include quotes in verbatim strings, double them
13string quoted = @"He said ""Hello""";

Raw String Literals (C# 11+)

For complex strings with quotes and special characters:

csharp
1// Raw string literal (three or more quotes)
2string json = """
3 {
4 "name": "Alice",
5 "age": 30
6 }
7 """;
8
9// Interpolated raw strings
10string name = "Alice";
11string data = $"""
12 Name: {name}
13 Status: Active
14 """;

Common String Properties and Methods

csharp
1string text = "Hello, World!";
2
3// Properties
4int length = text.Length; // 13
5
6// Case conversion
7string upper = text.ToUpper(); // HELLO, WORLD!
8string lower = text.ToLower(); // hello, world!
9
10// Searching
11bool contains = text.Contains("World"); // true
12int index = text.IndexOf("World"); // 7
13bool starts = text.StartsWith("Hello"); // true
14bool ends = text.EndsWith("!"); // true
15
16// Extracting
17string sub = text.Substring(0, 5); // Hello
18char first = text[0]; // H
19
20// Modifying (returns new string)
21string replaced = text.Replace("World", "C#"); // Hello, C#!
22string trimmed = " hello ".Trim(); // hello

String Comparison

csharp
1string a = "hello";
2string b = "Hello";
3
4// Case-sensitive comparison
5bool equal1 = a == b; // false
6bool equal2 = a.Equals(b); // false
7
8// Case-insensitive comparison
9bool equal3 = a.Equals(b, StringComparison.OrdinalIgnoreCase); // true
10bool equal4 = string.Equals(a, b, StringComparison.OrdinalIgnoreCase); // true

Null and Empty Strings

csharp
1string empty = "";
2string nullString = null;
3string whitespace = " ";
4
5// Checking for empty or null
6bool isEmpty = string.IsNullOrEmpty(empty); // true
7bool isNullOrEmpty = string.IsNullOrEmpty(nullString); // true
8bool hasContent = string.IsNullOrWhiteSpace(whitespace); // true
9
10// Safe way to work with potentially null strings
11string name = null;
12int length = name?.Length ?? 0; // 0 (null-conditional + null-coalescing)

Building Strings Efficiently

For many concatenations, use StringBuilder:

csharp
1using System.Text;
2
3// Inefficient for many concatenations
4string result = "";
5for (int i = 0; i < 1000; i++)
6{
7 result += i + ", "; // Creates new string each time
8}
9
10// Efficient alternative
11StringBuilder 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.