Reversing a string
rikki cattermole
rikki at cattermole.co.nz
Fri Jan 11 08:15:01 UTC 2019
So strings in D are Unicode. This is both a great thing and a horrible
thing.
To reverse a Unicode string correctly you need to take into account BiDi
and graphemes, in other words it gets rather complex. However I suspect
that this isn't what you want.
Now a (w/d)string is defined as:
alias string = immutable(char)[];
alias wstring = immutable(wchar)[];
alias dstring = immutable(dchar)[];
Note the immutable, it means you cannot modify individual values. Which
is a problem for reverse because it modifies in place.
Which means:
writeln("Hello D".reverse);
Won't work, but:
writeln("Hello D".dup.reverse);
Will. A simple duplication (char[]) makes it work.
Finally, arrays in D are absolutely brilliant. They are what we call
slices. A slice is a pointer + a length. That is it. Hence they cannot
be reversed in place. Of course this is great for interacting with e.g.
C, since its just a matter of slicing any data back to get your bounds
checking ext.
More information about the Digitalmars-d-learn
mailing list