你可以使用这个扩展方法:
private static readonly HashSet<UnicodeCategory> SeparatorCharCategories = new HashSet<UnicodeCategory>{ UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.DecimalDigitNumber };
public static String SeparateCharCategories(this string input, string delimiter = " ")
{
StringBuilder sb = new StringBuilder(input.Length);
UnicodeCategory lastCharCategory = Char.GetUnicodeCategory(input[0]);
for(int i = 0; i < input.Length; i++)
{
UnicodeCategory charCategory = Char.GetUnicodeCategory(input[i]);
if (lastCharCategory != charCategory && SeparatorCharCategories.Contains(charCategory))
sb.Append(delimiter);
sb.Append(input[i]);
lastCharCategory = charCategory;
}
return sb.ToString();
}
您的样本和其他极端情况:
var items = new[] { "CustomerName", "CustomerID", "ContactNumber", "PurchaseOrders", "purchaseOrders", "The2Unlimited", "Unlimited2", "222Unlimited", "The222Unlimited", "Unlimited222", "ATeam", "TheATeam", "TeamA", "HTMLGuide", "TheHTMLGuide", "TheGuideToHTML", "HTMLGuide5", "TheHTML5Guide", "TheGuideToHTML5", "TheUKAllStars", "AllStarsUK", "UKAllStars" };
foreach (string str in items)
Console.WriteLine(str.SeparateCharCategories(" "));
您看到不支持首字母缩略词,所以HTMLGuide 仍然是HTMLGuide:
Customer Name
Customer ID
Contact Number
Purchase Orders
purchase Orders
The 2 Unlimited
Unlimited 2
222 Unlimited
The 222 Unlimited
Unlimited 222
ATeam
The ATeam
Team A
HTMLGuide
The HTMLGuide
The Guide To HTML
HTMLGuide 5
The HTML 5 Guide
The Guide To HTML 5
The UKAll Stars
All Stars UK
UKAll Stars