string (Alias ของ System.String) เป็น Immutable Reference Type** — ค่าไม่เปลี่ยนแปลงได้หลังสร้าง ทุก Operation ที่ "เปลี่ยน" สตริง จะสร้าง Instance ใหม่
Properties
| Property | คำอธิบาย |
Length | จำนวน Char (UTF-16 Code Units) |
Chars[int index] | Indexer — เข้าถึง Char ตำแหน่ง index (Read-only) |
Methods สำคัญ (Static & Instance)
Comparison
| Method | คำอธิบาย |
Compare(strA, strB) | เปรียบเทียบ คืน -1, 0, 1 (Ordinal) |
Compare(strA, strB, ignoreCase) | เปรียบเทียบ Ignore Case |
Equals(strA, strB) | เท่ากับหรือไม่ (Static) |
str.Equals(other, StringComparison) | เท่ากับหรือไม่ (Instance, ระบุ Rule) |
Concatenation
| Method | คำอธิบาย |
Concat(str0, str1) | ต่อ 2 สตริง |
Concat(str0, str1, str2) | ต่อ 3 สตริง |
Concat(params string[]) | ต่อ Array ของสตริง |
Join(separator, strings[]) | ต่อ Array ใส่ Separator (นิยมมาก) |
Search & Extract
| Method | คำอธิบาย |
IndexOf/LastIndexOf | หาตำแหน่ง Substring/Char |
Contains | มี Substring หรือไม่ |
StartsWith/EndsWith | ขึ้นต้น/ลงท้ายด้วย |
Substring(start, length?) | ตัด Substring |
Split(separator[]) | แยกเป็น Array |
Transform
| Method | คำอธิบาย |
ToUpper/ToLower | พิมพ์ใหญ่/เล็ก (Culture-Aware) |
Trim/TrimStart/TrimEnd | ตัด Whitespace |
Replace(old, new) | แทนที่ Substring |
Insert/Remove | แทรก/ลบ ตำแหน่ง |
PadLeft/PadRight | Padding ด้วย Char |
ตัวอย่างการใช้งาน
using System;
class StringDemo {
static void Main() {
// Join Array
string[] lines = {
"Cricket is my life",
"It is played between two teams",
"It has three formats",
"T20, Test Cricket and ODI",
"Cricket is life"
};
string joined = String.Join("\n", lines);
Console.WriteLine(joined);
// Comparison
Console.WriteLine(String.Compare("apple", "banana")); // -1
Console.WriteLine("Apple".Equals("apple", StringComparison.OrdinalIgnoreCase)); // True
// Search
string text = "Hello World";
Console.WriteLine(text.IndexOf("World")); // 6
Console.WriteLine(text.Contains("World")); // True
// Transform
Console.WriteLine(" hello ".Trim()); // "hello"
Console.WriteLine("hello".Replace('l', 'x')); // "hexxo"
Console.WriteLine("5".PadLeft(3, '0')); // "005"
Console.ReadKey();
}
}
StringBuilder — เมื่อต้อง Mutate หลายครั้ง
using System.Text;
// ❌ ร้าย: สร้าง String ใหม่ทุก Loop
string s = "";
for (int i = 0; i < 1000; i++) s += i;
// ✅ ดี: Mutable Buffer
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.Append(i);
string result = sb.ToString();
String Interpolation (C# 6+)
string name = "John";
int age = 30;
string formatted = $"Name: {name}, Age: {age}, Next Year: {age + 1}";
// "Name: John, Age: 30, Next Year: 31"
Raw String Literals (C# 11+)
// Multi-line ไม่ต้อง Escape
string json = """
{
"name": "John",
"age": 30
}
""";
สรุป
string = Immutable, Unicode (UTF-16), Reference Type
- ใช้
StringBuilder สำหรับ Concatenation ใน Loop
- ใช้
StringComparison.OrdinalIgnoreCase สำหรับ Compare ที่ไวและชัดเจน
- ใช้
String.Join แทน Loop + Concatenation
- C# 11+: Raw String Literals สำหรับ Multi-line/JSON/Regex