Is there a more elegant way to do this in D?

WebFreak001 d.forum at webfreak.org
Thu Apr 8 12:19:29 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.  I can think of two brute force methods of doing 
> this.  I found an answer to something similar in the forum and 
> adapted it - but it is so much code for such a simple procedure:
>
> ```d
> import std;
> void main()
> {
>     auto a = [1,0,1,1,1,0,1,0,1,1,1,1,0];
>
>     string b = to!string(a.map!(to!string)
>      .chunks(a.length)
>      .map!join);
>
>     string f = b[2..b.length-2];  //needed to strip the first 
> two and las two characters
>     writeln(f);
>
> }
> ```
>
> I want to come out of this with a string that looks like this: 
> 1011101011110
>
> Thanks in advance.

```d
string to01String(int[] x) @safe
{
     auto conv = x.to!(ubyte[]); // allocates new array, so later 
cast to string is OK
     conv[] += '0'; // assume all numbers are 0-9, then this gives 
the correct result
     return (() @trusted => cast(string)conv)();
}
```


More information about the Digitalmars-d-learn mailing list