Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Xử lý chuỗi

String vs StringBuilder

// String - immutable
string s1 = "Hello";
string s2 = s1 + " World"; // Tạo string mới

// StringBuilder - mutable (hiệu quả cho nhiều thao tác)
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
string result = sb.ToString(); // "Hello World"

// Khi nào dùng StringBuilder?
// - Nhiều string concatenations trong loop
// - Xây dựng string động từ nhiều phần
// - Hiệu suất quan trọng

String Interpolation

string name = "Alice";
int age = 30;

// String interpolation (C# 6+)
string message = $"Hello, {name}. You are {age} years old.";

// Format specifiers
decimal price = 19.99m;
string formatted = $"Price: {price:C}"; // "Price: $19.99"
string percent = $"Discount: {0.15:P}"; // "Discount: 15.00%"

// Expression trong interpolation
string status = $"User is {(age >= 18 ? "adult" : "minor")}";

String Methods

string text = "  Hello World  ";

// Common operations
string trimmed = text.Trim(); // "Hello World"
string upper = text.ToUpper(); // "  HELLO WORLD  "
string lower = text.ToLower(); // "  hello world  "

// Searching
bool contains = text.Contains("Hello"); // true
int index = text.IndexOf("World"); // 9
bool startsWith = text.StartsWith("  Hello"); // true
bool endsWith = text.EndsWith("World  "); // true

// Splitting và joining
string[] parts = "a,b,c".Split(',');
string joined = string.Join("-", parts); // "a-b-c"

// Formatting
string formatted = string.Format("{0} is {1} years old", name, age);