Convert LowerCase and UpperCase to TitleCase in C#

Feb 10, 2010 Posted by Lara Kannan
Question is...
Convert LowerCase and UpperCase to TitleCase in C#

The String class has the ToLower() and the ToUpper() methods to convert a string to lowercase and uppercase respectively.

However when it comes to converting the string to TitleCase, the ToTitleCase() method of the TextInfo class comes very handy. Let me demonstrate this with an example:


class Program
{
static void Main(string[] args)
{
string strLow = "lower case";
string strT = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strLow);
Console.WriteLine("Lower Case to Title Case: " + strT);

string strCap = "UPPER CASE";
strT = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCap.ToLower());
Console.WriteLine("Upper Case to Title Case: " + strT);
Console.ReadLine();
}
}

Make sure you import the System.Globalization namespace. As you can observe, we are using the CurrentCulture.TextInfo property to retrieve an instance of the TextInfo class based on the current culture.

Note:
As mentioned on the site, "this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym". This is the reason why we first convert strCap to lower case and then supply the lowercase string to ToTitleCase() in the following manner:

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCap.ToLower());

Share
Labels: ,

Post a Comment