"strtok" D equivalent

pascal111 judas.the.messiah.111 at gmail.com
Thu Jul 28 23:42:43 UTC 2022


On Thursday, 28 July 2022 at 23:16:15 UTC, Paul Backus wrote:
> On Thursday, 28 July 2022 at 21:52:28 UTC, pascal111 wrote:
>> On Thursday, 28 July 2022 at 20:36:31 UTC, Paul Backus wrote:
>>> ```d
>>> import std.algorithm: filter;
>>> import std.range: empty;
>>> import std.functional: not;
>>>
>>> // ...
>>>
>>>     auto tokens = input
>>>         .splitter!(c => delimiters.canFind(c))
>>>         .filter!(not!empty);
>>>
>>> // ...
>>> ```
>>
>> I think "tokens" is a range. I didn't read much about it, but 
>> I figured out that there's no particular way to know the 
>> number of elements in a range, or how can you know the 
>> elements order and the length of the range?
>
> In this case, the only way is to convert the range to an array, 
> using [`std.array.array`][1]:
>
> ```d
> import std.array: array;
>
> // ...
>
>     string[] tokens = input
>         .splitter!(c => delimiters.canFind(c))
>         .filter!(not!empty)
>         .array;
> ```
>
> [1]: https://phobos.dpldocs.info/std.array.array.1.html

What about this version:

string[] d_strtok(const string ch, const string delim)
{

     string[] tokens = ch.
     splitter!(c => delim.canFind(c)).
     filter!(not!empty).array;

     return tokens;
}


////////////////////////


module main;

import std.stdio;
import std.string;
import std.conv;
import dcollect;
import std.math;
/*import std.algorithm;
import std.range: empty;
import std.functional: not;
import std.array;*/

int main(string[] args)
{

     string bad_guy="This is,, an, statement.";
     string[] coco=d_strtok(bad_guy, " ,.");

     for(int i=0; i<coco.length; i++)
         writeln(coco[i]);

	return 0;
}

//////////////////

Really I don't understand all of its code well although it works 
fine.


More information about the Digitalmars-d-learn mailing list