Tuesday, December 1, 2009

Proper Case Function in C#

I found this proper case function but had no way to comment on how to improve it so I will post it in my blog. There are times when you want to capitalize words with hyphens such as capitalizing the S in Ann-Smith. I modified the function as follows:


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.IsPunctuation(chThis))
            fEmptyBefore = true; // treat punctuations as spaces
        else
        {
            if (Char.IsLetter(chThis) && fEmptyBefore)
                chThis = Char.ToUpper(chThis);
            else
                chThis = Char.ToLower(chThis);
            fEmptyBefore = false;
        }
        sb.Append(chThis);
    }
    return sb.ToString();

} 


As you can see, the section with the comment "treat punctuations as spaces" was added to handle these situations.

Other Possible Improvements: Handling words such as McDonald.


Adiel

No comments:

Post a Comment