我写了以下扩展方法.随意使用它们.
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)
计算机绝对没有办法神奇地知道"麦当劳"中的第一个"D"应该大写.所以,我认为有两种选择.
那里的某个人可能有一个软件或一个库可以为你做这件事.
除此之外,您唯一的选择是采取以下方法:首先,我会在具有"有趣"大写字母的词典中查找名称.显然你必须自己提供这本词典,除非已经存在.其次,应用一种算法来纠正一些明显的算法,比如以O'和Mac和Mc开头的凯尔特人的名字,虽然给出了足够多的名字,这样的算法无疑会产生很多误报.最后,将每个不符合前两个标准的名字的第一个字母大写.
| 归档时间: |
|
| 查看次数: |
4379 次 |
| 最近记录: |