Monday, January 18, 2010

Converting Input Text to Title Case in .net

We are so used to TitleCases in word processor applications. When it comes to string manipulation in .net, the only options for case conversion options available seems to be as follows:

1. Change Text to Lower case
2. Change Text to Upper Case

We need sometime to convert our text to Title Case in our .net applications. There are two options available out of the box.

1. Using TextInfo class available in CultureInfo in System.Globalization namespace.
2. Using StrConv function avaliable in Microsoft.VisualBasic.

Here StrConv is a port of VB6 to .net. So most of us developers don't prefer to use it. If you are planning to use it in C# code, you would have to reference Microsoft.VisualBasic.

Dim text As String = "tEXT fOR cASE cONVERSION"
Dim convertedText As String = StrConv(text, VbStrConv.ProperCase)

As discussed, TextInfo is generally the most preferred option. To use TextInfo, we have to get a CultureInfo object. We might get it from current thread for the culture of the environment of thread being executed. We might also get TextInfo object by creating in instance of CultureInfo explicitly. The example code using StrConv() is as follows:

System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo
Dim text As String = "tEXT fOR cASE cONVERSION"
Dim textCaseConverter As TextInfo =
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo
Dim textAfterCaseConversion As String = textCaseConverter.ToTitleCase(text)

We might also get an instance of TextInfo explicitly as follows:

Dim culture As New System.Globalization.CultureInfo("en-US", False)

Remember that there is one limitation when are using TextInfo to convert to Title Cases. It returns nothing when the input text is all upper case. This can be worked around by changing the text to any of upper / lower case before inputting it to the toTitleCase() method.

Note:
In addition to converting input text to Title case, TextInfo also supports converting text to upper and lower cases.

2 comments:

Anonymous said...

For the case of all captial text, I think you meant to say "it does not perform any conversion" rather than "It returns nothing" because it does return the original string.

Muhammad Shujaat Siddiqi said...

You are right. Thanks for clarification.