Convert all first letter to upper case, rest lower for each word Convert all first letter to upper case, rest lower for each word asp.net asp.net

Convert all first letter to upper case, rest lower for each word


string s = "THIS IS MY TEXT RIGHT NOW";s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());


I probably prefer to invoke the ToTitleCase from CultureInfo (System.Globalization) than Thread.CurrentThread (System.Threading):

string s = "THIS IS MY TEXT RIGHT NOW";s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

But it should be the same as jspcal's solution.

EDIT

Actually, those solutions are not the same: CurrentThread --calls--> CultureInfo!


System.Threading.Thread.CurrentThread.CurrentCulture

string s = "THIS IS MY TEXT RIGHT NOW";s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());IL_0000:  ldstr       "THIS IS MY TEXT RIGHT NOW"IL_0005:  stloc.0     // sIL_0006:  call        System.Threading.Thread.get_CurrentThreadIL_000B:  callvirt    System.Threading.Thread.get_CurrentCultureIL_0010:  callvirt    System.Globalization.CultureInfo.get_TextInfoIL_0015:  ldloc.0     // sIL_0016:  callvirt    System.String.ToLowerIL_001B:  callvirt    System.Globalization.TextInfo.ToTitleCaseIL_0020:  stloc.0     // s

System.Globalization.CultureInfo.CurrentCulture

string s = "THIS IS MY TEXT RIGHT NOW";s = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());IL_0000:  ldstr       "THIS IS MY TEXT RIGHT NOW"IL_0005:  stloc.0     // sIL_0006:  call        System.Globalization.CultureInfo.get_CurrentCultureIL_000B:  callvirt    System.Globalization.CultureInfo.get_TextInfoIL_0010:  ldloc.0     // sIL_0011:  callvirt    System.String.ToLowerIL_0016:  callvirt    System.Globalization.TextInfo.ToTitleCaseIL_001B:  stloc.0     // s

References:


There are a couple of ways to go about converting the first character of a string to upper case.

The first way is to create a method that simply caps the first character and appends the rest of the string using a substring:

public string UppercaseFirst(string s){    return char.ToUpper(s[0]) + s.Substring(1);}

The second way (which is slightly faster) is to split the string into a character array and then rebuild the string:

public string UppercaseFirst(string s){    char[] a = s.ToCharArray();    a[0] = char.ToUpper(a[0]);    return new string(a);}