← C# EnglishChapter 09 of 13

Strings

## Learning Objectives - Manipulate strings - Use string interpolation - Work with StringBuilder - Master string methods ## String Basics ### Declaration ```csharp string name = "Alice"; string empty = ""; string nullStr = null; string empty2 = string.Empty; ``` ### Immutability ```csharp // Strings are immutable - operations create new strings string s = "Hello"; s = s + " World"; // Creates new string, s is now "Hello World" ``` ## String Operations ### Concatenation ```csharp string first = "Hello"; string second = "World"; string combined = first + " " + second; // "Hello World" string combined2 = string.Concat(first, " ", second); string combined3 = string.Join(" ", first, second); // "Hello World" ``` ### String Methods ```csharp string text = " Hello, World! "; text.Length; // 17 (with spaces) text.Trim(); // "Hello, World!" text.TrimStart(); // "Hello, World! " text.TrimEnd(); // " Hello, World!" text.ToLower(); // " hello, world! " text.ToUpper(); // " HELLO, WORLD! " text.Trim().ToLower(); // Chained ``` ### Searching ```csharp string text = "Hello, World!"; text.IndexOf("World"); // 7 text.IndexOf("world"); // -1 (case-sensitive) text.LastIndexOf("o"); // 8 text.Contains("World"); // true text.StartsWith("Hello"); // true text.EndsWith("!"); // true ``` ### Substring ```csharp string text = "Hello, World!"; text.Substring(7); // "World!" text.Substring(0, 5); // "Hello" text.Substring(7, 5); // "World" ``` ### Split and Join ```csharp string csv = "Alice,Bob,Charlie"; string[] names = csv.Split(','); // ["Alice", "Bob", "Charlie"] string joined = string.Join(", ", names); // "Alice, Bob, Charlie" // Split with RemoveEmptyEntries string text = "One,,Two,,Three"; string[] parts = text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); ``` ### Replace ```csharp string text = "Hello, World!"; text.Replace("World", "C#"); // "Hello, C#!" text.Replace("o", "0"); // "Hell0, W0rld!" text.Replace(" ", ""); // "Hello,World!" ``` ### Pad and Trim ```csharp string num = "42"; num.PadLeft(5, '0'); // "00042" num.PadRight(5, '0'); // "42000" // Trim specific characters string text = "###Hello###"; text.Trim('#'); // "Hello" text.TrimStart('#'); // "Hello###" text.TrimEnd('#'); // "###Hello" ``` ## String Interpolation (C# 6+) ### Basic Syntax ```csharp string name = "Alice"; int age = 30; string message = $"Name: {name}, Age: {age}"; // "Name: Alice, Age: 30" ``` ### Expressions ```csharp int a = 5, b = 3; Console.WriteLine($"{a} + {b} = {a + b}"); // "5 + 3 = 8" Console.WriteLine($"{a} * {b} = {a * b}"); // "5 * 3 = 15" Console.WriteLine($"{{literal}}"); // "{literal}" ``` ### Formatting ```csharp decimal price = 19.99m; DateTime today = DateTime.Now; Console.WriteLine($"Price: {price:C}"); // "Price: $19.99" Console.WriteLine($"Date: {today:yyyy-MM-dd}"); // "Date: 2024-01-15" Console.WriteLine($"Pi: {Math.PI:F2}"); // "Pi: 3.14" Console.WriteLine($"{42:D5}"); // "00042" ``` ### Raw String Literal (C# 11+) ```csharp string json = """ { "name": "Alice", "age": 30 } """; string path = $""" C:\Users\{Environment.UserName}\Documents """; ``` ## StringBuilder ### When to Use ```csharp // Bad for many concatenations string result = ""; for (int i = 0; i < 1000; i++) { result += i.ToString(); // Creates 1000 strings! } // Good - mutable string StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.Append(i); } string result = sb.ToString(); ``` ### StringBuilder Methods ```csharp StringBuilder sb = new StringBuilder(); sb.Append("Hello"); // "Hello" sb.AppendLine(); // "Hello\n" sb.AppendLine("World"); // "Hello\nWorld\n" sb.AppendFormat("{0:C}", 19.99m); // Append formatted sb.Length; // Current length sb.Clear(); // Clear all sb.Remove(0, 5); // Remove characters sb.Insert(0, "Start "); // Insert at position sb.Replace("World", "C#"); // Replace text ``` ### StringBuilder Initialization ```csharp StringBuilder sb = new StringBuilder(); StringBuilder sb2 = new StringBuilder(100); // Initial capacity StringBuilder sb3 = new StringBuilder("Hello", 100); ``` ## String Comparison ### Options ```csharp string a = "Hello"; string b = "hello"; // Case-sensitive comparison bool equal = a == b; // false bool equalIgnoreCase = a.Equals(b, StringComparison.OrdinalIgnoreCase); // true // String.Compare int result = string.Compare(a, b); // 1 (a > b) int result2 = string.Compare(a, b, StringComparison.OrdinalIgnoreCase); // 0 // CompareTo int result3 = a.CompareTo(b); // 1 ``` ### StringComparison Enum | Value | Description | |-------|-------------| |.Ordinal | Binary, case-sensitive | | OrdinalIgnoreCase | Binary, case-insensitive | | CurrentCulture | Uses culture info, case-sensitive | | CurrentCultureIgnoreCase | Uses culture info, case-insensitive | ## null String Handling ### Safe Operations ```csharp string? nullStr = null; // Safe methods that don't throw nullStr?.Length; // null nullStr ?? "default"; // "default" nullStr?.ToUpper(); // null // Checking for null if (!string.IsNullOrEmpty(nullStr)) { Console.WriteLine(nullStr); } if (!string.IsNullOrWhiteSpace(nullStr)) { Console.WriteLine(nullStr); } ``` ### string.IsNullOrEmpty vs string.IsNullOrWhiteSpace ```csharp string.Empty; // IsNullOrEmpty: true, IsNullOrWhiteSpace: true null; // IsNullOrEmpty: true, IsNullOrWhiteSpace: true " "; // IsNullOrEmpty: false, IsNullOrWhiteSpace: true "hello"; // IsNullOrEmpty: false, IsNullOrWhiteSpace: false ``` ## Char Operations ### Working with Characters ```csharp string text = "Hello"; foreach (char c in text) { Console.WriteLine(c); } char first = text[0]; // 'H' char.IsDigit(first); // false char.IsLetter(first); // true char.IsUpper(first); // true char.ToLower(first); // 'h' ``` ## String Pooling ### Interning ```csharp // Compiler interns string literals string a = "Hello"; string b = "Hello"; Console.WriteLine(a == b); // true (same reference) Console.WriteLine(ReferenceEquals(a, b)); // true // But not for runtime strings string c = new string("Hello".ToCharArray()); Console.WriteLine(a == c); // true (value equal) Console.WriteLine(ReferenceEquals(a, c)); // false ``` ## Summary - Strings are immutable - operations create new strings - String methods: IndexOf, Contains, Split, Replace, Substring - String interpolation: $"Hello, {name}" - Use StringBuilder for many concatenations - null handling: `??` and `?.` operators - string.IsNullOrEmpty/IsNullOrWhiteSpace for checks - Case-insensitive: use StringComparison

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →