Is there a native Proper Case string function in C#?

Viewed 34711

I was about to write my own C# extension to convert a string to Proper Case (i.e. capitalize the first letter of every word), then I wondered if there's not a native C# function to do just that... is there?

5 Answers
String s  = "yOu caN Use thIs"

s = System.Threading.Thread.CurrentThread
           .CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

The main limitation I can see with this is that it's not "true" title case. i.e. In the phrase "WaR aNd peaCe", the "and" part should be lowercase in English. This method would capitalise it though.

This should work.

public static string ToTitleCase(this string strX)
{
    string[] aryWords = strX.Trim().Split(' ');

    List<string> lstLetters = new List<string>();
    List<string> lstWords = new List<string>();

    foreach (string strWord in aryWords)
    {
        int iLCount = 0;
        foreach (char chrLetter in strWord.Trim())
        {
            if (iLCount == 0)
            {
                lstLetters.Add(chrLetter.ToString().ToUpper());
            }
            else
            {
                lstLetters.Add(chrLetter.ToString().ToLower());
            }
            iLCount++;
        }
        lstWords.Add(string.Join("", lstLetters));
        lstLetters.Clear();
    }

    string strNewString = string.Join(" ", lstWords);

    return strNewString;
}
Related