Title Case: Viết hoa chữ cái đầu của mỗi từ, các từ nhỏ (and, of, the...) có thể giữ nguyên tùy style. .NET cung cấp TextInfo.ToTitleCase trong System.Globalization.
Cách cơ bản
using System.Globalization;
using System.Threading;
string input = "wAr aNd pEaCe";
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
string titleCase = textInfo.ToTitleCase(input.ToLower()); // ToLower trước để chuẩn hóa
Console.WriteLine(titleCase); // War And Peace
Lưu ý quan trọng
ToTitleCasekhông chuyển toàn bộ sang lowercase trước. Nên gọi.ToLower()trước.- Không xử lý "minor words" (and, of, the, in...) tự động -> tất cả từ đều viết hoa chữ đầu.
- Không xử lý apostrophe tốt:
"o'brien"->"O'Brien"(OK), nhưng"don't"->"Don'T"(sai). - Không hỗ trợ Unicode full case mapping cho một số ngôn ngữ.
Ví dụ nhiều chuỗi
string[] values = {
"a tale of three cities",
"gROWL rescue",
"inside the office",
"sports and tennis",
"THE RETURN OF CHRISTMAS HOLMES"
};
TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
foreach (var value in values)
{
string normalized = value.ToLower(); // Chuẩn hóa
string result = ti.ToTitleCase(normalized);
Console.WriteLine($"{value} --> {result}");
}
Kết quả
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
Cải tiến: Title Case thông minh (bỏ qua minor words)
static readonly HashSet MinorWords = new(StringComparer.OrdinalIgnoreCase)
{
"a", "an", "the", "and", "but", "or", "for", "nor",
"on", "at", "to", "from", "by", "in", "of", "vs", "via"
};
public static string ToSmartTitleCase(string input, CultureInfo culture = null)
{
if (string.IsNullOrWhiteSpace(input)) return input;
culture ??= CultureInfo.CurrentCulture;
TextInfo ti = culture.TextInfo;
string[] words = input.ToLower(culture).Split(' ', StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < words.Length; i++)
{
if (i == 0 || i == words.Length - 1 || !MinorWords.Contains(words[i]))
words[i] = ti.ToTitleCase(words[i]);
}
return string.Join(" ", words);
}
// Test
Console.WriteLine(ToSmartTitleCase("a tale of three cities")); // A Tale of Three Cities
Console.WriteLine(ToSmartTitleCase("the return of the king")); // The Return of the King
Extension Method tiện lợi
public static class StringExtensions
{
public static string ToTitleCase(this string input, CultureInfo culture = null)
{
if (string.IsNullOrWhiteSpace(input)) return input;
culture ??= CultureInfo.CurrentCulture;
return culture.TextInfo.ToTitleCase(input.ToLower(culture));
}
}
// Usage
Console.WriteLine("hello world".ToTitleCase()); // Hello World