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

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 11 12:22:16 PST 2016


On 02/11/2016 04:44 AM, 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, " "));
> }
>

You can use element format specifiers:

     writeln(format("%(%s %)", parts));

writefln understands that too:

     writefln("%(%s %)", parts);

Ali

[1] http://dlang.org/phobos/std_format.html#.formattedWrite
[2] 
http://ddili.org/ders/d.en/formatted_output.html#ix_formatted_output.%%28



More information about the Digitalmars-d-learn mailing list