compareNatural function

int compareNatural (String a, String b)

Compares strings a and b according to natural sort ordering.

A natural sort ordering is a lexical ordering where embedded numerals (digit sequences) are treated as a single unit and ordered by numerical value. This means that "a10b" will be ordered after "a7b" in natural ordering, where lexical ordering would put the 1 before the 7, ignoring that the 1 is part of a larger number.

Example: The following strings are in the order they would be sorted by using this comparison function:

"a", "a0", "a0b", "a1", "a01", "a9", "a10", "a100", "a100b", "aa"

Implementation

int compareNatural(String a, String b) {
  for (int i = 0; i < a.length; i++) {
    if (i >= b.length) return 1;
    var aChar = a.codeUnitAt(i);
    var bChar = b.codeUnitAt(i);
    if (aChar != bChar) {
      return _compareNaturally(a, b, i, aChar, bChar);
    }
  }
  if (b.length > a.length) return -1;
  return 0;
}