Is there a more elegant way to do this in D?
Paul Backus
snarwin at gmail.com
Thu Apr 8 04:53:00 UTC 2021
On Thursday, 8 April 2021 at 03:57:23 UTC, Brad wrote:
> I am trying to take an array and convert it to a string. I
> know that Split will let me easily go the other way. I
> searched for the converse of Split but have not been able to
> locate it.
You need two functions here:
1. `joiner` [1], which lazily joins the elements of a range.
2. `array` [2], which eagerly evaluates a range and returns an
array of its elements.
The final code looks like this:
dchar[] b = a.map!(to!string).joiner.array;
You may have noticed that the type of `b` here is `dchar[]`, not
`string`. This is due to a feature of D's standard library known
as "auto decoding" [3]. To prevent the strings you get from
`to!string` from being auto-decoded into ranges of `dchar`, you
can use the function `std.utf.byCodeUnit` [4], like this:
string b = a.map!(to!string).map!(byCodeUnit).joiner.array;
[1]
https://phobos.dpldocs.info/std.algorithm.iteration.joiner.1.html
[2] https://phobos.dpldocs.info/std.array.array.1.html
[3] https://jackstouffer.com/blog/d_auto_decoding_and_you.html
[4] https://phobos.dpldocs.info/std.utf.byCodeUnit.html
More information about the Digitalmars-d-learn
mailing list