String joining an array of structs or class instances implementing toString?

Edwin van Leeuwen via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 11 04:53:20 PST 2016


On Thursday, 11 February 2016 at 12:44:15 UTC, pineapple wrote:
> It feels like there should be an out-of-the box way to do this 
> but I haven't been able to find it? Help?
>
> This is the thing that I want to do:
>
> struct example{
>     const string str;
>     //this(string str){ this.str = str; }
>     string toString(){
>         return this.str;
>     }
> }
>
> public void main(){
>     import std.stdio;
>     import std.string;
>     example[] parts = [example("hello"), example("world")];
>     writeln(std.string.join(parts, " "));
> }

I'd do it like this:

import std.algorithm : map;
pars.map!((part) => part.toString) // Turn them to strings
  .join(" ").writeln; // Join them.


More information about the Digitalmars-d-learn mailing list