endsWith - for a string vs an array of strings

FG via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 10 13:50:08 PST 2015


On 2015-01-10 at 21:58, bearophile wrote:
> Needles is not an array type, it's a type tuple, so withOneOfThese doesn't accept an array of strings. [...]
> So if you really want to pack the strings in some kind of unity, you can do this as workaround: [...]

I would suggest create a function that does the same thing as endsWith(Range, Needles...) but instead of Needles expanded as a list of arguments it takes in a range of them. In fact I was surprised that there was no such function in std.algorithm present. Therefore I have written endsWithAny for this purpose a moment ago. Is it any good? Please correct if necessary.




import std.array;
import std.string;
import std.stdio;
import std.range;

uint endsWithAny(alias pred = "a == b", Range, Needles)(Range haystack, Needles needles)
     if (isBidirectionalRange!Range && isInputRange!Needles &&
     is(typeof(.endsWith!pred(haystack, needles.front)) : bool))
{
     foreach (i, e; needles)
         if (endsWith!pred(haystack, e))
             return i + 1;
     return 0;
}


void main(string[] args)
{
     string[] test = ["1", "two", "three!"];
     auto a = "arghtwo".endsWithAny(test);
     writefln("%s", a);
}

unittest
{
     string[] hs = ["no-one", "thee", "there were three", "two"];
     string[] tab = ["one", "two", "three"];
     assert(endsWithAny(hs[0], tab) == 1);
     assert(endsWithAny(hs[1], tab) == 0);
     assert(endsWithAny(hs[2], tab) == 3);
     assert(endsWithAny(hs[3], tab) == 2);
}


More information about the Digitalmars-d-learn mailing list