splitter

Lazily splits a range using an element as a separator. This can be used with any narrow string type or sliceable range type, but is most popular with string types.

Two adjacent separators are considered to surround an empty element in the split range. Use filter!(a => !a.empty) on the result to compress empty elements.

The predicate is passed to std.functional.binaryFun, and can either accept a string, or any callable that can be executed via pred(element, s).

If the empty range is given, the result is a range with one empty element. If a range with one separator is given, the result is a range with two empty elements.

If splitting a string on whitespace and token compression is desired, consider using splitter without specifying a separator (see fourth overload below).

  1. auto splitter(Range r, Separator s)
    splitter
    (
    alias pred = "a == b"
    Range
    Separator
    )
    (
    Range r
    ,
    Separator s
    )
    if (
    is(typeof(binaryFun!pred(r.front, s)) : bool) &&
    (
    (
    hasSlicing!Range &&
    hasLength!Range
    )
    ||
    isNarrowString!Range
    )
    )
  2. auto splitter(Range r, Separator s)
  3. auto splitter(Range input)
  4. auto splitter(C[] s)

Parameters

pred

The predicate for comparing each element with the separator, defaulting to "a == b".

r
Type: Range

The input range to be split. Must support slicing and .length.

s
Type: Separator

The element to be treated as the separator between range segments to be split.

Constraints: The predicate pred needs to accept an element of r and the separator s.

Return Value

Type: auto

An input range of the subranges of elements between separators. If r is a forward range or bidirectional range, the returned range will be likewise.

Examples

1 import std.algorithm.comparison : equal;
2 
3 assert(equal(splitter("hello  world", ' '), [ "hello", "", "world" ]));
4 int[] a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ];
5 int[][] w = [ [1, 2], [], [3], [4, 5], [] ];
6 assert(equal(splitter(a, 0), w));
7 a = [ 0 ];
8 assert(equal(splitter(a, 0), [ (int[]).init, (int[]).init ]));
9 a = [ 0, 1 ];
10 assert(equal(splitter(a, 0), [ [], [1] ]));
11 w = [ [0], [1], [2] ];
12 assert(equal(splitter!"a.front == b"(w, 1), [ [[0]], [[2]] ]));

See Also

std.regex._splitter for a version that splits using a regular expression defined separator.

Meta