ProperCase function in C#

I’ve seen a lot of variants of this function, while being really simple it allows for a lot of different solutions.
For example, solutions with regular expressions are quite popular floating around the web but the solution I use is so simple:

public static string ProperCase(string stringInput)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            bool fEmptyBefore = true;
            foreach (char ch in stringInput)
            {
                char chThis = ch;
                if (Char.IsWhiteSpace(chThis))
                    fEmptyBefore = true;
                else
                {
                    if (Char.IsLetter(chThis) && fEmptyBefore)
                        chThis = Char.ToUpper(chThis);
                    else
                        chThis = Char.ToLower(chThis);
                    fEmptyBefore = false;
                }
                sb.Append(chThis);
            }
            return sb.ToString();
        }

it will turn all these cases:

string s1 = ProperCase(“STefan HOLMBERG”); s1 = ProperCase(“stefan holmberg”); s1 = ProperCase(“steFan holmberg”);

into Stefan Holmberg

While this solution

string sName = Microsoft.VisualBasic.Strings.StrConv("stefan holmberg sweden . You bet. this is a cool function",
 Microsoft.VisualBasic.Constants.vbProperCase,0);

-e using the VisualBasic runtime functions from within C# is possible – and also quite nice – you need to remember to add a reference to Microsoft.VisualBasic.dll in order to use it

 

3 Responses to “ProperCase function in C#”

  1. Krishan says:

    string myString = “aDaNi gRoUp limiTED.”;

    System.Globalization.TextInfo TI = new System.Globalization.CultureInfo(“en-US”, false).TextInfo;

    Response.Write(TI.ToTitleCase(myString));

  2. Daniel Banda says:

    //Get the culture property of the thread.
    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    //Create TextInfo object.
    TextInfo textInfo = cultureInfo.TextInfo;

    //Convert to uppercase.
    Console.WriteLine(textInfo.ToUpper(title));
    //Convert to lowercase.
    Console.WriteLine(textInfo.ToLower(title));
    //Convert to title case.
    Console.WriteLine(textInfo.ToTitleCase(title));

  3. thanks to both Krishan and Daniel. It was some really old code of mine – and I was really surprised to see in the docs
    “Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0″ = it has been supported forever…

Leave a Response