[phobos] I'd like this snippet add to std.format. Refines are welcome.

Zhuo Nengwen soarowl at yeah.net
Mon Dec 18 01:42:54 UTC 2017


import std.array, std.format, std.stdio;

string ctformat(const string s, const char beginDelimiter = '{', 
const char endDelimiter = '}')
{
     auto f = appender!string;
     string[] params;
     for (auto i = 0; i < s.length; i++)
     {
         auto c = s[i];
         if (c != beginDelimiter)
             f ~= c;
         else
         {
             i++;
             auto param = appender!string;
             while (i < s.length)
             {
                 auto n = s[i];
                 if (n == endDelimiter)
                     break;
                 param ~= n;
                 i++;
             }
             params ~= param.data;
         }
     }

     return format("format(`%s`, %s)", f.data, join(params, ", "));
}

void main()
{
     const name = "Bill";
     const numbers = 1000;
     const s = mixin(ctformat(`Hi, %{name}s! I have 
%,4?{'_'}{numbers}b bottles of beer.`));
     writeln(s);
}



More information about the phobos mailing list