我建议将字符串拆分成块,每个块要么全是数字,要么不是数字:"B01 001" -> {"B", "01", " ", "001"}
.
然后比较这些块(比较两个全数字块是特例).
Code:(Fiddle)
public sealed class NaturalComparer : IComparer<string> {
private static int CompareChunks(string x, string y) {
if (x[0] >= '0' && x[0] <= '9' && y[0] >= '0' && y[0] <= '9') {
string tx = x.TrimStart('0');
string ty = y.TrimStart('0');
int result = tx.Length.CompareTo(ty.Length);
if (result != 0)
return result;
result = tx.CompareTo(ty);
if (result != 0)
return result;
}
return string.Compare(x, y);
}
public int Compare(string? x, string? y) {
if (ReferenceEquals(x, y))
return 0;
if (x is null)
return -1;
if (y is null)
return +1;
var itemsX = Regex
.Split(x, "([0-9]+)")
.Where(item => !string.IsNullOrEmpty(item))
.ToList();
var itemsY = Regex
.Split(y, "([0-9]+)")
.Where(item => !string.IsNullOrEmpty(item))
.ToList();
for (int i = 0; i < Math.Min(itemsX.Count, itemsY.Count); ++i) {
int result = CompareChunks(itemsX[i], itemsY[i]);
if (result != 0)
return result;
}
return itemsX.Count.CompareTo(itemsY.Count);
}
}
Demo:个
string[] demo = new string[] {
"B01 002",
"B01 0010",
"01",
"B01 001",
"B10 001",
"B01 01",
"1",
"B1 001",
"B02 001",
"A1"
};
Array.Sort(demo, new NaturalComparer());
Console.WriteLine(string.Join(Environment.NewLine, demo));
Output:个
01
1
A1
B01 001
B01 01
B01 002
B01 0010
B1 001
B02 001
B10 001