Convert LowerCase and UpperCase to TitleCase in .NET

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:

C#

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();
}
}

VB.NET

Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim strLow As String = "lower case"
Dim strT As String=CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strLow)
Console.WriteLine("Lower Case to Title Case: " & strT)

Dim strCap As String = "UPPER CASE"
strT = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCap.ToLower())
Console.WriteLine("Upper Case to Title Case: " & strT)
Console.ReadLine()
End Sub
End Class

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());

The output after running the code is as shown below:

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: