Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mcdonalds to ProperCase in C#

Tags:

string

c#

How would you convert names to proper case in C#?

I have a list of names that I'd like to proof.

For example: mcdonalds to McDonalds or o'brien to O'Brien.

like image 237
ob213 Avatar asked Sep 24 '09 16:09

ob213


2 Answers

I wrote the following extension methods. Feel free to use them.

public static class StringExtensions
{
  public static string ToProperCase( this string original )
  {
    if( original.IsNullOrEmpty() )
      return original;

    string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );
    return result;
  }

  public static string WordToProperCase( this string word )
  {
    if( word.IsNullOrEmpty() )
      return word;

    if( word.Length > 1 )
      return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );

    return word.ToUpper( CultureInfo.CurrentCulture );
  }

  private static readonly Regex _properNameRx = new Regex( @"\b(\w+)\b" );

  private static readonly string[] _prefixes = { "mc" };

  private static string HandleWord( Match m )
  {
    string word = m.Groups[1].Value;

    foreach( string prefix in _prefixes )
    {
      if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )
        return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();
    }

    return word.WordToProperCase();
  }
}
like image 152
Eddie Velasquez Avatar answered Oct 18 '22 14:10

Eddie Velasquez


You could consider using a search engine to help you. Submit a query and see how the results have capitalized the name.

like image 37
tster Avatar answered Oct 18 '22 13:10

tster