array to string functional?
SrMordred
patric.dexheimer at gmail.com
Fri Sep 14 20:43:45 UTC 2018
On Friday, 14 September 2018 at 19:44:37 UTC, berni wrote:
> a) I've got an int[] which contains only 0 und 1. And I want to
> end with a string, containing 0 and 1. So [1,1,0,1,0,1] should
> become "110101". Of course I can do this with a loop and ~. But
> I think it should be doable with functional style, which is
> something I would like to understand better. Can anyone help me
> here? (I think a.map!(a=>to!char(a+'0')) does the trick, but is
> this good style or is there a better way?)
>
> b) After having this I'd like to split this resulting string
> into chunks of a fixed length, e.g. length 4, so "110101" from
> above should become ["1101","01"]. Again, is it possible to do
> that with functional style? Probably chunks from std.range
> might help here, but I don't get it to work.
>
> All in all, can you fill in the magic functional chain below?
>
>> auto a = [1,0,1,1,1,0,1,0,1,1,1,1,0];
>>
>> auto result = magic functional chain here :-)
>>
>> assert(result==["1011","1010","1111","0"]);
What you want is std.range.chunks
auto a = [1,0,1,1,1,0,1,0,1,1,1,1,0];
a.map!(to!string)
.join("")
.chunks(4)
.map!(to!string) //don´t know why the chunks are not already
strings at this point ;/
.writeln;
More information about the Digitalmars-d-learn
mailing list