Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created August 30, 2022 08:46
Show Gist options
  • Save ramonsmits/31ca039e1c76133ea136435b2c1def76 to your computer and use it in GitHub Desktop.
Save ramonsmits/31ca039e1c76133ea136435b2c1def76 to your computer and use it in GitHub Desktop.
NaturalComparer to compare string with numerics
//
// Based on https://stackoverflow.com/a/5641272/199551
//
public class NaturalComparer : IComparer<string>
{
public static readonly NaturalComparer Instance = new NaturalComparer();
private NaturalComparer() { }
public int Compare(string x, string y)
{
if (x == null && y == null) return 0;
if (x == null) return -1;
if (y == null) return 1;
int lx = x.Length, ly = y.Length;
for (int mx = 0, my = 0; mx < lx && my < ly; mx++, my++)
{
if (char.IsDigit(x[mx]) && char.IsDigit(y[my]))
{
long vx = 0, vy = 0;
for (; mx < lx && char.IsDigit(x[mx]); mx++)
vx = vx * 10 + x[mx] - '0';
for (; my < ly && char.IsDigit(y[my]); my++)
vy = vy * 10 + y[my] - '0';
if (vx != vy)
return vx > vy ? 1 : -1;
}
if (mx < lx && my < ly && x[mx] != y[my])
return x[mx] > y[my] ? 1 : -1;
}
return lx - ly;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment