Task to throw away string parts, use joiner and splitter not very successful

monarch_dodra monarchdodra at gmail.com
Thu Jan 2 07:56:48 PST 2014


On Thursday, 2 January 2014 at 15:50:10 UTC, monarch_dodra wrote:
> On Wednesday, 1 January 2014 at 07:40:40 UTC, Dfr wrote:
>> And one more problem here:
>>
>>    string name = "test";
>>    auto nameparts = splitter(name, '.');
>>    writeln(typeof(joiner(nameparts, ".").array).stringof);
>>
>> This prints "dchar[]", but i need char[] or string, how to get 
>> my 'string' back ?
>
> It's actually because "joiner" returns a range of dchar. It's 
> kind of inefficient actually. If you instead write a minimal 
> "RangeJoiner", you can get:

Pressed "sent" too soon. Anywas, as I was saying, joiner operates 
on RoR, so will return elements (dchar) individually. You *could* 
do a bit better with a "simpleJoiner", which will return strings 
at once:

//----
auto simpleJoiner(R, E)(R r, E e)
if (isInputRange!R && is(CommonType!(E, ElementType!R)))
{
     static struct Result
     {
         private alias ElementType = CommonType!(E, 
.ElementType!R);
         private R r;
         private E e;
         private bool re = true;

         bool empty() @property
         {
             return r.empty;
         }

         ElementType front() @property
         {
             return re ? r.front : e;
         }

         void popFront()
         {
             if (re) r.popFront();
             re = !re;
         }

         static if (isForwardRange!R) Result save() @property
         {
             return Result(r.save, e);
         }
     }
     return Result(r, e);
}
//----

Using this will produce "string at once" elements, rather than 
dchars at once, which is a bit more efficient. It can also help 
depending on how you want to "visualize" the data you are 
handling.

Also note, if all you want to do is print, there is no reason at 
all call "array", simply format your range with "%-(%s%)":

//----
void main()
{
     writefln("%-(%s%)",
         "this.is.a.test"
         .splitter('.')
         .dropBack(1)
         .joiner(".") //or simpleJoiner(".")
     );
}
//----

In both case, it'll produce:
//----
this.is.a
//----

If you want to know, "%(" and "%)" means "range-mode-print. The 
%s inside is the individual element format, and "%-(" means 
"natural" print. Read more about it here:
http://dlang.org/phobos/std_format.html


More information about the Digitalmars-d-learn mailing list