countUntil

Counts elements in the given forward range until the given predicate is true for one of the given needles.

  1. auto countUntil(R haystack, Rs needles)
  2. ptrdiff_t countUntil(R haystack, N needle)
    ptrdiff_t
    countUntil
    (
    alias pred = "a == b"
    R
    N
    )
    if (
    is(typeof(binaryFun!pred(haystack.front, needle)) : bool)
    )
  3. ptrdiff_t countUntil(R haystack)

Parameters

pred

The predicate for determining when to stop counting.

haystack R

The input range to be counted.

Return Value

Type: ptrdiff_t

The number of elements which must be popped from the front of haystack before reaching an element for which startsWith!pred(haystack, needles) is true. If startsWith!pred(haystack, needles) is not true for any element in haystack, then -1 is returned. If more than one needle is provided, countUntil will wrap the result in a tuple similar to Tuple!(ptrdiff_t, "steps", ptrdiff_t needle)

Examples

assert(countUntil("hello world", "world") == 6);
assert(countUntil("hello world", 'r') == 8);
assert(countUntil("hello world", "programming") == -1);
assert(countUntil("日本語", "本語") == 1);
assert(countUntil("日本語", '語')   == 2);
assert(countUntil("日本語", "五") == -1);
assert(countUntil("日本語", '五') == -1);
assert(countUntil([0, 7, 12, 22, 9], [12, 22]) == 2);
assert(countUntil([0, 7, 12, 22, 9], 9) == 4);
assert(countUntil!"a > b"([0, 7, 12, 22, 9], 20) == 3);

// supports multiple needles
auto res = "...hello".countUntil("ha", "he");
assert(res.steps == 3);
assert(res.needle == 1);

// returns -1 if no needle was found
res = "hello".countUntil("ha", "hu");
assert(res.steps == -1);
assert(res.needle == -1);
import std.ascii : isDigit;
import std.uni : isWhite;

assert(countUntil!(isWhite)("hello world") == 5);
assert(countUntil!(isDigit)("hello world") == -1);
assert(countUntil!"a > 20"([0, 7, 12, 22, 9]) == 3);

See Also

Meta