Need help: Return reference slice

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 30 08:03:53 PDT 2014


On 10/29/14 3:50 PM, advibm wrote:
> Hello,
>
> I would like to create a D function that returns a slice of a string.
> This slice shall be a reference to a part of the string argument.
> Is this generally possible in D?
>
> This is the function:
> auto ref betweenTwoStrings(T)(inout T src, string start, string end) {
>    long a = src.countUntil(start);
>    if (a < 0)
>      return src; // null
>    a += start.length;
>    long b = src[a..$].countUntil(end);
>    if (b < 0)
>      return src; // null
>    b += a;
>    return src[a..b];
> }
>
>
> I would like to have something like that:
>
> char[] buf; // already filled array
> char[] partOfBuf = betweenTwoStrings(buf, "START", "END");
> partOfBuf[0] = 'a'; // THIS should also change the 'buf' variable
> assert(buf[0] == 'a');
>
> Thanks for your help


How I would do it:

inout(T)[] betweenTwoStrings(T, U, V)(inout(T)[] src, const(U)[] start, 
const(V)[] end) if(allSatisfy!(isSomeChar, T, U, V)) {
   long a = src.countUntil(start);
   if (a < 0)
     return src; // null
   a += start.length;
   long b = src[a..$].countUntil(end);
   if (b < 0)
     return src; // null
   b += a;
   return src[a..b];
}

This should accept any kind of strings, in any constancy for all the 
parameters, yet guarantee it does not change any data in any of them.

-Steve.


More information about the Digitalmars-d-learn mailing list