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:
Tweet
No comments:
Post a Comment