Thursday, April 19, 2007

C# String ToTitleCase – intial letter capitalization of the string

To convert string to title case (capitalize initial letters of the string), there is not string method to call. However, we can use the CultureInfo from Globalization and use the TextInfo’s ToTitleCase method. Here is how it can be done in C#:

public static string ToTitleCase(string inputString)

{

System.Globalization.CultureInfo cultureInfo =

System.Threading.Thread.CurrentThread.CurrentCulture;

System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;

return textInfo.ToTitleCase(inputString.ToLower());

}

Simple enough and self explanatory…

Love coding!

4 comments:

langtudien said...

public string ToNameCase(string Name)
{
string strTemp = Name.ToLower().Trim();
while (strTemp.IndexOf(" ") != -1) //Contains 2 continued space characters
{
strTemp= strTemp.Replace(" ", " ");// Replace 2 spaces by 1 space
}

System.Globalization.CultureInfo cultureInfo =

System.Threading.Thread.CurrentThread.CurrentCulture;

System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;

return textInfo.ToTitleCase(strTemp.ToLower());


}

Anonymous said...

There is no need to call ToLower(). The ToTitleCase works well even if the string is in all upper case or in mixed casing.

Or am I wrong?

Oggmeister said...

Yep - you definitely have to call ToLower() for ToTitleCase() to work.

A Booth said...

Or you could just reference Microsoft.VisualBasic

and do: destination = Strings.StrConv( source, VbStrConv.ProperCase, 0 );