Skip to main content

natural_cmp

Function natural_cmp 

Source
pub(crate) fn natural_cmp(a: &str, b: &str) -> Ordering
Expand description

Compares two strings using natural sort order so that embedded numbers sort by value rather than by their string representation (“9” < “10” < “100”).

Each string is split into alternating runs of numeric and non-numeric characters. A numeric token is an integer optionally followed by a decimal part (.<digits>), so "4.5" is treated as a single number rather than the three segments 4, ., 5. Numeric tokens are compared as f64 values, which means leading zeros are ignored (“01” == “1”) and fractional parts are respected (“4” < “4.5” < “5”). Non-numeric runs are compared lexicographically. When one run is numeric and the other is text, the numeric segment sorts first.

§Examples

// This example uses private API; doc tests cannot access non-public items.
use std::cmp::Ordering;

// Numeric runs compare by value, not string length.
assert_eq!(natural_cmp("9", "10"), Ordering::Less);
assert_eq!(natural_cmp("100", "99"), Ordering::Greater);

// Fractional numbers are supported.
assert_eq!(natural_cmp("Vol 4", "Vol 4.5"), Ordering::Less);
assert_eq!(natural_cmp("Vol 4.5", "Vol 5"), Ordering::Less);

// Leading zeros are ignored: "01" and "1" are numerically equal.
assert_eq!(natural_cmp("01", "1"), Ordering::Equal);

// Mixed strings compare segment by segment.
assert_eq!(natural_cmp("Chapter 9", "Chapter 10"), Ordering::Less);