Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีแปลง String เป็น Title Case (ตัวแรกใหญ่) ใน C#

Title Case คือการทำให้ตัวอักษรแรกของแต่ละคำเป็นตัวใหญ่ (Capitalize) ส่วนตัวอื่นเป็นตัวเล็ก ใช้สำหรับชื่อเรื่อง ชื่อตัวละคร หัวข้อ ฯลฯ

ใน .NET ใช้ TextInfo.ToTitleCase จาก System.Globalization

ตัวอย่างพื้นฐาน

using System;
using System.Globalization;

static void Main()
{
    string input = "wAr aNd pEaCe";
    
    // ใช้ CultureInfo.CurrentCulture หรือ 지정 Culture
    TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
    // หรือ TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
    
    string titleCase = textInfo.ToTitleCase(input);
    Console.WriteLine($"\"{input}\" → \"{titleCase}\"");
    // Output: "wAr aNd pEaCe" → "War And Peace"
}

ตัวอย่างหลายคำ

static void Main()
{
    string[] values = 
    {
        "a tale of three cities",
        "gROWL rescue",
        "inside the office",
        "sports and tennis",
        "THE RETURN OF CHRISTMAS HOLMES",
        "mr. smith goes to washington"
    };
    
    TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
    
    foreach (var value in values)
    {
        Console.WriteLine($"{value,-35} → {ti.ToTitleCase(value)}");
    }
}

ผลลัพธ์

a tale of three cities              → A Tale Of Three Cities
gROWL rescue                        → Growl Rescue
inside the office                   → Inside The Office
sports and tennis                   → Sports And Tennis
THE RETURN OF CHRISTMAS HOLMES      → The Return Of Christmas Holmes
mr. smith goes to washington        → Mr. Smith Goes To Washington

ข้อจำกัดของ ToTitleCase

  • ไม่จัดการ "Minor Words": คำเล็ก (and, of, the, in, to, a, an) จะถูก Capitalize ทุกคำ (ไม่ใช่ True Title Case ตาม Style Guide)
  • ไม่รองรับ Apostrophes: o'neill → O'Neill (OK) แต่ don't → Don'T (ผิด!)
  • Acronyms: xml parser → Xml Parser (อาจต้องการ XML Parser)
  • Non-Latin Scripts: อาจทำงานไม่ถูกต้องกับบางภาษา

Custom Title Case (Advanced)

public static class TitleCaseHelper
{
    private static readonly HashSet MinorWords = new(StringComparer.OrdinalIgnoreCase)
    {
        "a", "an", "the", "and", "but", "or", "for", "nor",
        "on", "at", "to", "from", "by", "in", "of", "vs", "vs."
    };
    
    public static string ToTitleCase(this string input, CultureInfo culture = null)
    {
        if (string.IsNullOrWhiteSpace(input)) return input;
        
        var ti = (culture ?? CultureInfo.CurrentCulture).TextInfo;
        var words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        
        for (int i = 0; i < words.Length; i++)
        {
            string word = words[i];
            bool isFirst = i == 0;
            bool isLast = i == words.Length - 1;
            bool isMinor = MinorWords.Contains(word.ToLowerInvariant());
            
            if (isFirst || isLast || !isMinor)
            {
                // Capitalize First Char, Lower Rest (Handle Apostrophe)
                words[i] = CapitalizeWord(word);
            }
            else
            {
                words[i] = word.ToLowerInvariant();
            }
        }
        
        return string.Join(" ", words);
    }
    
    private static string CapitalizeWord(string word)
    {
        if (string.IsNullOrEmpty(word)) return word;
        
        var sb = new StringBuilder(word.Length);
        bool capitalizeNext = true;
        
        foreach (char c in word)
        {
            if (capitalizeNext && char.IsLetter(c))
            {
                sb.Append(char.ToUpperInvariant(c));
                capitalizeNext = false;
            }
            else
            {
                sb.Append(char.ToLowerInvariant(c));
            }
            
            // หลัง Apostrophe ให้ Capitalize ต่อ (O'Neill)
            if (c == '\'' || c == '’')
                capitalizeNext = true;
        }
        
        return sb.ToString();
    }
}

// ใช้งาน
string s = "the lord of the rings: the return of the king";
Console.WriteLine(s.ToTitleCase()); 
// "The Lord of the Rings: The Return of the King"

ใน .NET 8+ / .NET Core

ยังคงใช้ TextInfo.ToTitleCase เดียวกัน ไม่มี Built-in Advanced Title Case

Library ภายนอก

  • Humanizer: "war and peace".Transform(To.TitleCase) (รองรับ Minor Words, Acronyms)
  • TitleCase (NuGet): Lightweight Title Case Library