dphobos

Shortest way to concatenate strings in D outside writefln()?


I repeadetly need to concatenate of format strings, and is wondering what is the shortest (or easiest to read) way to concatenate strings outside of the writefln() function, in D?

That is, I like the behaviour of writefln, where you can do for example:

// Some code to init y="2013", m="01", d="02" ...
writefln("%s-%s-%s", y, m, d);

... but I want to do this without writing it out on stdout. Is there an equally simple way?

The only think I found was the format function in std.string, but that requires you to provide string buffer of predefined length as the first argument, which is inconvenient most of the time.

The other alternative I found out was to do (by use of "join" in std.array):

// Some code to init y="2013", m="01", d="02" ...
datestr = [y, m, d].join("-");

... which is quite handy, but only works if you use the same "separator" of course.

Any more general way to do this, that is shorter than the above examples, and don't require providing a predefined-length buffer string?


Solution

  • You seem to confuse format with sformat. format does exactly what you want:

    datestr = format("%s-%s-%s", y, m, d);
    

    Even better: to catch potential mismatches between the format-string and the arguments, at compile-time instead of run-time:

    datestr = format!"%s-%s-%s"(y, m, d);
    

    The most basic way to concatenate strings would be with ~:

    datestr = y ~ "-" ~ m ~ "-" ~ d;
    

    More on that: http://dlang.org/arrays.html#array-concatenation