mcdonalds到C#中的ProperCase

ob2*_*213 11 c# string

如何在C#中将名称转换为正确的大小写?

我有一个我要证明的名单.

例如:mcdonalds到McDonalds或o'brien到O'Brien.

tst*_*ter 9

您可以考虑使用搜索引擎来帮助您.提交查询并查看结果如何将名称大写.

  • 我从来没有真正做到过.听起来像新实习生的任务! (2认同)

Edd*_*uez 8

我写了以下扩展方法.随意使用它们.

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();
  }
}
Run Code Online (Sandbox Code Playgroud)


Gre*_*ley 7

计算机绝对没有办法神奇地知道"麦当劳"中的第一个"D"应该大写.所以,我认为有两种选择.

  1. 那里的某个人可能有一个软件或一个库可以为你做这件事.

  2. 除此之外,您唯一的选择是采取以下方法:首先,我会在具有"有趣"大写字母的词典中查找名称.显然你必须自己提供这本词典,除非已经存在.其次,应用一种算法来纠正一些明显的算法,比如以O'和Mac和Mc开头的凯尔特人的名字,虽然给出了足够多的名字,这样的算法无疑会产生很多误报.最后,将每个不符合前两个标准的名字的第一个字母大写.

  • 请不要使用'Mac'做虚拟方法.我的名字经常被愚蠢的邮件系统致残. (6认同)
  • @MaciejTrybiło:MacHines会这样做你做的. (4认同)