ภาพรวม
ใช้ Substring(0, 10) ดึง substring ตัวแรก 10 ตัวอักษร ต้องตรวจสอบความยาวก่อนเพื่อป้องกัน Exception
โค้ดตัวอย่าง
using System;
public class Demo {
public static void Main() {
string str = "Cricket is a religion in India!";
// วิธีที่ 1: Substring (ต้องเช็ค Length ก่อน)
string result1 = str.Length >= 10 ? str.Substring(0, 10) : str;
Console.WriteLine($"Substring: '{result1}'");
// วิธีที่ 2: LINQ Take
string result2 = new string(str.Take(10).ToArray());
Console.WriteLine($"Take(10): '{result2}'");
// วิธีที่ 3: String.Create (C# 9+, high performance)
string result3 = str.Length >= 10 ? str[..10] : str; // Range operator
Console.WriteLine($"Range [..10]: '{result3}'");
}
}
ผลลัพธ์
Substring: 'Cricket is'
Take(10): 'Cricket is'
Range [..10]: 'Cricket is'
วิธีที่ทันสมัย: Range Operator (C# 8+)
string str = "Hello World";
string first10 = str.Length >= 10 ? str[..10] : str; // 0..10
string last5 = str.Length >= 5 ? str[^5..] : str; // Last 5
string middle = str.Length > 10 ? str[5..10] : ""; // 5 to 9
Safe Substring Extension Method
public static class StringExtensions {
public static string FirstChars(this string s, int count) {
if (string.IsNullOrEmpty(s) || count <= 0) return "";
return s.Length <= count ? s : s[..count];
}
public static string LastChars(this string s, int count) {
if (string.IsNullOrEmpty(s) || count <= 0) return "";
return s.Length <= count ? s : s[^count..];
}
}
// ใช้งาน
string s = "Hello";
Console.WriteLine(s.FirstChars(10)); // "Hello" (ไม่ throw)
Console.WriteLine(s.FirstChars(3)); // "Hel"
กรณีพิเศษ: Unicode Grapheme Clusters
using System.Globalization;
string s = "👨👩👧👦Hello"; // 1 grapheme + 5 chars
var si = new StringInfo(s);
// ดึง 2 text elements แรก
string first2 = si.SubstringByTextElements(0, 2);
Console.WriteLine(first2); // 👨👩👧👦H
สรุป
| วิธี | Syntax | Safe for Short String | Performance |
|---|---|---|---|
| Substring | str.Substring(0, 10) | ไม่ (ต้องเช็ค Length) | ดี |
| Range Operator | str[..10] | ไม่ (ต้องเช็ค Length) | ดี (ไม่ allocate เพิ่มในบางกรณี) |
| LINQ Take | new string(str.Take(10).ToArray()) | ได้ (คืนค่าที่มี) | ช้ากว่า |
| Extension Method | str.FirstChars(10) | ได้ (ปลอดภัย) | ดี |