คลาส String ใน C# มีคุณสมบัติ (Properties) หลัก 2 อย่าง:
| ลำดับ | คุณสมบัติ & คำอธิบาย |
| 1 | Chars — ดึงอ็อบเจ็กต์ Char ที่ตำแหน่งที่ระบุในสตริงปัจจุบัน (indexer: str[index]) |
| 2 | Length — ดึงจำนวนตัวอักษรในสตริงปัจจุบัน |
ตัวอย่างที่ 1: ใช้ Chars และ Length วนลูปตรวจสอบตัวอักษร
using System;
public class Demo
{
public static void Main()
{
string str1 = "h8b9";
string str2 = "abcdef";
Console.WriteLine("Is string1 null or empty? = " + string.IsNullOrEmpty(str1));
Console.WriteLine("Is string2 null or empty? = " + string.IsNullOrEmpty(str2));
bool val = str1 != str2;
Console.WriteLine("Is str1 equal to str2? = " + val);
for (int i = 0; i < str1.Length; i++)
{
if (Char.IsLetter(str1[i]))
Console.WriteLine(str1[i] + " is a letter");
else
Console.WriteLine(str1[i] + " is a number");
}
}
}
ผลลัพธ์
Is string1 null or empty? = False
Is string2 null or empty? = False
Is str1 equal to str2? = True
h is a letter
8 is a number
b is a letter
9 is a number
ตัวอย่างที่ 2: Length กับสตริงว่าง และ IsNullOrWhiteSpace
using System;
public class Demo
{
public static void Main()
{
string str1 = "hijklm";
string str2 = String.Empty;
Console.WriteLine("Is string1 null or whitespace? = " + String.IsNullOrWhiteSpace(str1));
Console.WriteLine("Is string2 null or whitespace? = " + String.IsNullOrWhiteSpace(str2));
Console.WriteLine("String1 length = " + str1.Length);
Console.WriteLine("String2 length = " + str2.Length); // บัคในต้นฉบับ: เขียน str1.Length ซ้ำ
Console.WriteLine("String length = " + "demo".Length);
}
}
ผลลัพธ์
Is string1 null or whitespace? = False
Is string2 null or whitespace? = True
String1 length = 6
String2 length = 0
String length = 4
สรุป
Length — คืนจำนวน ตัวอักษร (chars) ไม่ใช่ไบต์ — สตริงว่างคืน 0
Chars[int index] (indexer) — เข้าถึง char ตำแหน่ง index (0-based) — read-only
string.IsNullOrEmpty(str) — true หาก str เป็น null หรือ ""
string.IsNullOrWhiteSpace(str) — true หาก str เป็น null, "", หรือ whitespace เท่านั้น (space, tab, newline, etc.)
- สตริงใน C# เป็น immutable — ไม่สามารถแก้ไขตัวอักษรได้ (
str[0] = 'X' compile error)
- ใช้
StringBuilder หากต้องแก้ไขสตริงหลายครั้ง
เมธอดสตริงที่เกี่ยวข้องและนิยมใช้
| เมธอด | คำอธิบาย |
| Substring(start, len) | ดึง substring |
| IndexOf / LastIndexOf | หาตำแหน่งตัวอักษร/สตริงย่อย |
| Contains | ตรวจสอบมี substring หรือไม่ |
| StartsWith / EndsWith | ตรวจสอบคำนำหน้า/คำต่อท้าย |
| ToUpper / ToLower / ToUpperInvariant / ToLowerInvariant | แปลงพิมพ์ใหญ่/เล็ก |
| Trim / TrimStart / TrimEnd | ตัด whitespace |
| Split / Join | แยก/รวมสตริง |
| Replace | แทนที่ substring |
| Format / Interpolation ($"") | จัดรูปแบบสตริง |