Text in D article

Chris Nicholson-Sauls ibisbasenji at gmail.com
Sun Nov 19 01:23:41 PST 2006


Pierre Rouleau wrote:
> One aspect is the string formatting.  Does D support string formatting 
> similar to Python's dictionary-based formatting like:
> 
> a_dict = {person_name : 'Daniel'}
> a_string = 'Hello %(person_name)s ! How are you?' % a_dict
> 

No, but it ought to be easy enought to make.  A quick hack at it:

# import cashew .utils .array ;
#
# char[] dictsub (char[] src, char[][char[]] dict) {
#   char[]  result ;
#   char[]* plug   ;
#   size_t  open   ,
#           close  ,
#           pos    ;
#
#   while (NOT_FOUND != (open = src.indexOf("%(", pos))) {
#     close   = src.indexOf(")", open) ;
#     result ~= src[pos .. open]       ;
#     pos     = close + 1              ;
#
#     if (null is (plug = src[open + 2 .. close] in dict)) {
#       throw new Exception("dictsub: invalid key " ~ src[open .. close + 1]);
#     }
#     result ~= *plug;
#   }
#   result ~= src[pos .. $];
# }

Don't quote me on that working exactly right as is, since its just off the top of my head. 
  But usage would be fairly straight forward, while not quite as pretty as Python since we 
don't yet have associative literals.

# char[][char[]] a_dict;
# a_dict["person_name"] = "Daniel";
# a_string = "Hello %(person_name)! How are you?".dictsub(a_dict);

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list