Need help: Return reference slice

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Oct 29 14:25:26 PDT 2014


On 10/29/2014 12: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

There are pretty useful std.algorithm functions for searching:

import std.algorithm;
import std.traits;
import std.array;

C[] betweenTwoStrings(C)(C[] src, string start, string end)
     if (isSomeChar!C)
{
     if (src.findSkip(start)) {
         auto found = src.findSplitBefore(end);

         // Just for readability:
         auto needleAndAfter = found[1];

         if (!needleAndAfter.empty) {
             auto beforeNeedle = found[0];
             return beforeNeedle;
         }
     }

     return (C[]).init;
}

void main()
{
     char[] buf;
     buf ~= "prefixSTARTactual partENDpostfix";

     char[] partOfBuf = betweenTwoStrings(buf, "START", "END");

     partOfBuf[] = 'a';
     assert(buf == "prefixSTARTaaaaaaaaaaaENDpostfix");
}

Ali



More information about the Digitalmars-d-learn mailing list