Có nhiều cách lấy ký tự đầu tiên của string trong C#:
Cách 1: Indexer (nhanh nhất, khuyên dùng)
string str = "Welcome to the Planet!"; char firstChar = str[0]; // 'W' Console.WriteLine(firstChar);
Cách 2: Substring
string first = str.Substring(0, 1); // Trả về string "W" Console.WriteLine(first);
Cách 3: LINQ First()
using System.Linq; char first = str.First(); // 'W' string firstStr = str.Take(1).ToString(); // Cần string.Join hoặc new string()
Ví dụ đầy đủ với kiểm tra rỗng
using System;
class Program
{
static void Main()
{
string str = "Welcome to the Planet!";
if (!string.IsNullOrEmpty(str))
{
// Cách tốt nhất
char c = str[0];
Console.WriteLine($"Ký tự đầu (char): {c}");
// Nếu cần string
string s = str.Substring(0, 1);
Console.WriteLine($"Ký tự đầu (string): {s}");
}
else
{
Console.WriteLine("Chuỗi rỗng!");
}
}
}
Kết quả đầu ra
Ký tự đầu (char): W Ký tự đầu (string): W
Lưu ý: Luôn kiểm tra string.IsNullOrEmpty trước khi truy cập str[0] để tránh IndexOutOfRangeException.