To convert string to title case (capitalize initial letters of the string), there is not string method to call. However, we can use the CultureInfo from Globalization and use the TextInfo’s ToTitleCase method. Here is how it can be done in C#:
public static string ToTitleCase(string inputString)
{
System.Globalization.CultureInfo cultureInfo =
System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
return textInfo.ToTitleCase(inputString.ToLower());
}
Simple enough and self explanatory…
Love coding!
4 comments:
public string ToNameCase(string Name)
{
string strTemp = Name.ToLower().Trim();
while (strTemp.IndexOf(" ") != -1) //Contains 2 continued space characters
{
strTemp= strTemp.Replace(" ", " ");// Replace 2 spaces by 1 space
}
System.Globalization.CultureInfo cultureInfo =
System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
return textInfo.ToTitleCase(strTemp.ToLower());
}
There is no need to call ToLower(). The ToTitleCase works well even if the string is in all upper case or in mixed casing.
Or am I wrong?
Yep - you definitely have to call ToLower() for ToTitleCase() to work.
Or you could just reference Microsoft.VisualBasic
and do: destination = Strings.StrConv( source, VbStrConv.ProperCase, 0 );
Post a Comment