Converting Text to Proper Case
Posted
Wed, Jul 22 2009 10:19
by
Deborah Kurata
When displaying text to the user as a title or message, you may want to ensure that the text is presented in proper case (also called title case).
If you are not familiar with the term “title case”, it basically means upper casing the first letter of each word as you would do in a proper title. For example: “Last Name” or “Customer Status Code”.
NOTE: Be sure to define a reference to System.Globalization.
In C#:
string sampleString = "this is a title";
CultureInfo currentCulture =
System.Threading.Thread.CurrentThread.CurrentCulture;
TextInfo currentInfo = currentCulture.TextInfo;
sampleString = currentInfo.ToTitleCase(sampleString);
In VB:
Dim sampleString As String = "this is a title"
Dim currentCulture As CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture
Dim currentInfo As TextInfo = currentCulture.TextInfo
sampleString = currentInfo.ToTitleCase(sampleString)
This code uses the CultureInfo to ensure that the casing is set appropriately based on the current culture. It then uses the ToTitleCase method of the TextInfo class to convert to the appropriate casing.
In VB there is another option to accomplish this task:
Dim sampleString As String = "this is a title"
sampleString = StrConv(sampleString, vbProperCase)
This code uses the StrConv function that is part of the Microsoft.VisualBasic namespace. This function could also be used from C# if you define a reference to the Microsoft.VisualBasic namespace.
The result is:
This Is A Title
Notice that this does not follow the proper case rules that define articles and conjunctions as lower case. Rather, it converts the first letter of every word to upper case and the remainder of the text to lower case.
Enjoy!