sort strings by interpreting them as integrals

Jonathan M Davis jmdavisProg at gmx.com
Sun Jul 29 19:32:59 PDT 2012


On Monday, July 30, 2012 04:09:18 Andrej Mitrovic wrote:
> void main()
> {
>     string[] x = ["_100", "_10", "_20"];
>     sort(x);
>     writeln(x);
> }

I have a solution, but I think that it uncovers a bug in sort:

import std.algorithm;
import std.stdio;

void main()
{
    string[] x = ["_100", "_10", "_20"];
    sort!"a.length < b.length ? true : a < b"(x);
    writeln(x);
}

I get an AssertError about it failing to sort, but the result is correct.

It _does_ assume that all numbers start with an underscore and don't have 
leading zeroes though. If you wanted the underscores to be optional or to 
allow them anywhere else other than the front (or if you allowed leading 
zeroes), then it gets considerably more complicated.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list