jQuery and ASP.NET

December 9, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Convert LowerCase and UpperCase to TitleCase in .NET"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions