Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d

phobos

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?

like image 913
Samuel Lampa Avatar asked Jan 02 '13 11:01

Samuel Lampa


1 Answers

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

like image 138
anonymous Avatar answered Oct 18 '22 02:10

anonymous