Tuesday, 21 August 2018

C#: Convert names to proper case

I have come across situations where some names or surnames have a character and managing casing is the important task. So i developed a simple method to convert the names to proper case in exceptional cases.

Ex: O'Brien , Tucky-Knight, Van Van, Nra (Nanette)

My method below identify the special character and make the next letter to upper case.


public string ConvertToProperNameCase(string input)
{
    char[] chars = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()).ToCharArray();

             for (int i = 0; i + 1 < chars.Length; i++)
             {
                 if ((chars[i].Equals('\'')) || (chars[i].Equals('-')) || (chars[i].Equals('(')) || (chars[i].Equals(' ')))
                 {
                     chars[i + 1] = Char.ToUpper(chars[i + 1]);
                 }
             }
    return new string(chars);
}

No comments:

Post a Comment