sorting a string

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 14 10:23:41 PDT 2017


On 7/14/17 12:43 PM, Anton Fediushin wrote:
> On Friday, 14 July 2017 at 15:56:49 UTC, Namal wrote:
>> Thx Steve! By sorting string I mean a function or series of functions 
>> that sorts a string by ASCII code, "cabA" to "Aabc" for instance.
> 
> import std.algorithm : sort;
> import std.stdio : writeln;
> 
> "cabA".dup.sort.writeln;
> 
> `dup` is used, because string cannot be modified, so a copy of string 
> used instead.

Don't do this, because it's not what you think. It's not actually 
calling std.algorithm.sort, but the builtin array sort property. This 
will be going away soon.

Annoyingly, because of autodecoding, you have to cast to ubytes via 
representation to do it the "proper" way:

import std.string: representation, assumeUTF;
import std.algorithm: sort;

auto bytes = line.representation.dup;
bytes.sort;
auto result = bytes.assumeUTF; // result is now char[]

-Steve


More information about the Digitalmars-d-learn mailing list