How to catenate a string multiple times ?

John Colvin john.loughran.colvin at gmail.com
Sat Mar 16 08:58:31 PDT 2013


On Saturday, 16 March 2013 at 15:29:03 UTC, Peter Sommerfeld 
wrote:
> Cannot find a reference: What is the best way
> to catenate a string multiple times ?
> Unfortunately this this does not work ;-)
>
> string tab = "..";
> tab = tab * 4; // -> "........"
>
> Peter

There are very many different ways of doing this, here are a few.

using template recursion:

//Repeats string "s" size_t "num" times at compile-time
template RepeatString (string s, size_t num)
{
     static if(num == 0)
         const RepeatString = "";
     else
         const RepeatString = s ~ RepeatString!(s, num-1);
}


or for fast runtime performance (also works at compile-time), 
something like this:

//appends any array to itself multiple times.
T[] concat(T)(T[] arr, size_t num_times)
{
     auto app = appender!(T[])(arr);
     app.reserve(num_times);

     foreach(i; 0..num_times)
         app ~= arr;

     return app.data;
}


simpler but slower:

T[] concat_slow(T)(T[] arr, size_t num_times)
{
     auto result = arr;
     foreach(i; 0..num_times)
         result ~= arr;
     return result;
}


If you needed extreme performance there are faster ways, but they 
are much longer and more complex.


More information about the Digitalmars-d-learn mailing list