"strtok" D equivalent

Paul Backus snarwin at gmail.com
Thu Jul 28 20:36:31 UTC 2022


On Thursday, 28 July 2022 at 19:17:26 UTC, pascal111 wrote:
> What's the "strtok" - C function - D equivalent?
>
> https://en.cppreference.com/w/cpp/string/byte/strtok

Closest thing is probably `std.algorithm.splitter` with a 
predicate:

```d
import std.algorithm: splitter, canFind;
import std.stdio;

void main()
{
     string input = "one + two * (three - four)!";
     string delimiters = "! +- (*)";
     auto tokens = input.splitter!(c => delimiters.canFind(c));
     foreach (token; tokens) {
         writef("\"%s\" ", token);
     }
}
```

Output:

```
"one" "" "" "two" "" "" "" "three" "" "" "four" "" ""
```

Unlike `strtok`, this code does not skip over sequences of 
multiple consecutive delimiters, so you end up with a bunch of 
empty tokens in the output. To exclude them, you can use 
`std.algorithm.filter`:

```d
import std.algorithm: filter;
import std.range: empty;
import std.functional: not;

// ...

     auto tokens = input
         .splitter!(c => delimiters.canFind(c))
         .filter!(not!empty);

// ...
```


More information about the Digitalmars-d-learn mailing list