startsWith

Checks whether the given input range starts with (one of) the given needle(s) or, if no needles are given, if its front element fulfils predicate pred.

  1. uint startsWith(Range doesThisStart, Needles withOneOfThese)
    uint
    startsWith
    (
    alias pred =
    (
    a
    ,
    b
    )
    => a == b
    Range
    Needles...
    )
    if (
    isInputRange!Range &&
    Needles.length > 1
    &&
    is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[0])) : bool)
    &&
    is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[1 .. $])) : uint)
    )
  2. bool startsWith(R1 doesThisStart, R2 withThis)
  3. bool startsWith(R doesThisStart, E withThis)
  4. bool startsWith(R doesThisStart)

Parameters

pred

Predicate to use in comparing the elements of the haystack and the needle(s). Mandatory if no needles are given.

doesThisStart Range

The input range to check.

withOneOfThese Needles

The needles against which the range is to be checked, which may be individual elements or input ranges of elements.

Return Value

Type: uint

0 if the needle(s) do not occur at the beginning of the given range; otherwise the position of the matching needle, that is, 1 if the range starts with withOneOfThese[0], 2 if it starts with withOneOfThese[1], and so on.

In the case where doesThisStart starts with multiple of the ranges or elements in withOneOfThese, then the shortest one matches (if there are two which match which are of the same length (e.g. "a" and 'a'), then the left-most of them in the argument list matches).

In the case when no needle parameters are given, return true iff front of doesThisStart fulfils predicate pred.

Examples

1 import std.ascii : isAlpha;
2 
3 assert("abc".startsWith!(a => a.isAlpha));
4 assert("abc".startsWith!isAlpha);
5 assert(!"1ab".startsWith!(a => a.isAlpha));
6 assert(!"".startsWith!(a => a.isAlpha));
7 
8 import std.algorithm.comparison : among;
9 assert("abc".startsWith!(a => a.among('a', 'b') != 0));
10 assert(!"abc".startsWith!(a => a.among('b', 'c') != 0));
11 
12 assert(startsWith("abc", ""));
13 assert(startsWith("abc", "a"));
14 assert(!startsWith("abc", "b"));
15 assert(startsWith("abc", 'a', "b") == 1);
16 assert(startsWith("abc", "b", "a") == 2);
17 assert(startsWith("abc", "a", "a") == 1);
18 assert(startsWith("abc", "ab", "a") == 2);
19 assert(startsWith("abc", "x", "a", "b") == 2);
20 assert(startsWith("abc", "x", "aa", "ab") == 3);
21 assert(startsWith("abc", "x", "aaa", "sab") == 0);
22 assert(startsWith("abc", "x", "aaa", "a", "sab") == 3);
23 
24 import std.typecons : Tuple;
25 alias C = Tuple!(int, "x", int, "y");
26 assert(startsWith!"a.x == b"([ C(1,1), C(1,2), C(2,2) ], [1, 1]));
27 assert(startsWith!"a.x == b"([ C(1,1), C(2,1), C(2,2) ], [1, 1], [1, 2], [1, 3]) == 2);

Meta

Suggestion Box / Bug Report