.Net 把句子變成 Title Case – .Net convert sentence to Title Case (This first Letter of the Word to Upper Case)

最近有一個任務..就是是要把一些 地址從大寫字母轉成 Title Case
E.g.
WELCOME TO SHARECHIWAI
轉成
Welcome To Sharechiwai
由為把他們insert入 Invoice上會有點怪怪的…
我第一個想到的方法是用 Excel上的ProperCase
但是如果可以寫一個程式來轉換便更好了…

解決方法十分簡單
我們可以使用TextInfoToTitleCase 這個功能去把文字轉換成Title Case E.G. 一個句子上的每個詞語上的第一個字母轉成大揩..其他的會轉換成小揩

string SampleText ="welcome to sharechiwai"
System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(SampleText);

溫馨提示:
由於這個功能遇到詞語上所有字都是大揩的話…這個功能不能打這些字轉成Title Case
所以我會建議大家用.ToLower()這個功能先把字母轉戶細揩…以方便轉成Title Case

Console.WriteLine("Original Text");
string OriginalText = "HELLO, WELCOME TO SHARECHIWAI";
Console.WriteLine(OriginalText);
Console.WriteLine();//newline

//Use Title Case from Original UpperCase Text
Console.WriteLine("Original UpperCase Text to TitleCase");
string TitleCaseInOriginalText =
	System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(OriginalText);
Console.WriteLine(TitleCaseInOriginalText);
Console.WriteLine();//newline

//Original To LowerCase then TitleCase
Console.WriteLine("Original To LowerCase then TitleCase");
string TitleCaseInLowerCaseOriginalText =
	System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(OriginalText.ToLower());
Console.WriteLine(TitleCaseInLowerCaseOriginalText);

Result
——-
Original Text
HELLO, WELCOME TO SHARECHIWAI

Original UpperCase Text to TitleCase
HELLO, WELCOME TO SHARECHIWAI

Original To LowerCase then TitleCase
Hello, Welcome To Sharechiwai

Sample output for convert text to TitleCase

Hope you find it useful

One thought on “.Net 把句子變成 Title Case – .Net convert sentence to Title Case (This first Letter of the Word to Upper Case)

  1. Leo Luis

    Hey Chi Wai Yau,

    This is Leo from the Philippines. How are you? I notice that you haven’t sent the pictures in my email. 🙂 Hope you have a safe flight back!

    Reply

Leave a Reply