การดึงตัวอักษรแรกของแต่ละคำ (Initials/Acronym) ใน C# ทำได้หลายวิธี
วิธีที่ 1: Split + Substring (Basic)
using System;
public class Program
{
public static void Main()
{
string str = "Never Give Up!";
string[] words = str.Split(' ', StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words)
{
if (word.Length > 0)
Console.Write(word[0]); // เร็วกว่า Substring(0,1)
}
// Output: NGU
}
}
วิธีที่ 2: LINQ (สั้นกระชับ)
using System.Linq;
string initials = string.Concat(
str.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Where(w => w.Length > 0)
.Select(w => w[0]));
Console.WriteLine(initials); // NGU
วิธีที่ 3: Regex (Complex Word Boundaries)
using System.Text.RegularExpressions;
string initials = string.Concat(
Regex.Matches(str, @"\b\w")
.Cast()
.Select(m => m.Value));
// หรือ
string initials = Regex.Replace(str, @"\B\w+", ""); // เก็บแค่ตัวแรกของแต่ละคำ
จัดการ Edge Cases
public static string GetInitials(string input, bool upperCase = true)
{
if (string.IsNullOrWhiteSpace(input)) return "";
var words = input.Split(new[] { ' ', '\t', '\n', '\r', '-', '_' },
StringSplitOptions.RemoveEmptyEntries);
var initials = words
.Where(w => w.Length > 0)
.Select(w => upperCase ? char.ToUpper(w[0]) : w[0]);
return string.Concat(initials);
}
// ทดสอบ
GetInitials("Never Give Up!") // "NGU"
GetInitials(" hello world ") // "HW"
GetInitials("C# Programming Language") // "CPL"
GetInitials("one-two_three") // "OTT"
กรณีใช้งานจริง
- สร้าง Acronym / Initials จากชื่อเต็ม
- Avatar Placeholder: แสดงตัวอักษรแรกของชื่อผู้ใช้
- Search Index: สร้าง Prefix สำหรับ Auto-complete
- Data Validation: ตรวจสอบรูปแบบรหัส (เช่น SKU)
Performance Note
word[0]เร็วกว่าword.Substring(0,1)(ไม่ allocate string ใหม่)StringSplitOptions.RemoveEmptyEntriesป้องกัน Empty String จาก Space หลายติดกัน- สำหรับ Performance Critical: ใช้
SpanManual Parsing