Remove filename from path

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 24 10:15:38 PDT 2014


On 09/24/2014 05:21 AM, monarch_dodra wrote:
> On Wednesday, 24 September 2014 at 10:35:29 UTC, Suliman wrote:
>> I can't understand how to use strip? For example I would like to cut
>> just extension.
>>
>> path = path.stripRight("exe");
>> Error: no overload matches for stripRight(C)(C[] str) if
>
> strip doens't work that way. It simply removes leading/trailing white.
>
> There's a version in std.algorithm which is more generic, but it accepts
> either a predicate, or an element, but not a range.
>
> Unfortunately, there is no generic function that allows striping of a
> specific ending range (though there are ways to either detect it, or
> strip it from the end).
> If you want something generic, then:
>
>      string path = "myFile.doc";
>      string extension = ".doc";
>      if (path.endsWith(extension))
>          path = path[0 .. $ - extension.length];
>
> Would work.

find() and friends can be used:

import std.algorithm;

void main()
{
     string path = "myFile.doc";
     string extension = ".doc";

     path = findSplitBefore(path, extension)[0];
     assert(path == "myFile");
}

And three retro()s make one modern(): :p

import std.algorithm;
import std.range;

void main()
{
     string path = "myFile.doc";
     string extension = ".doc";

     path = findSplitAfter(path.retro,
                           extension.retro)
            [1].retro;

     assert(path == "myFile");
}

Ali



More information about the Digitalmars-d-learn mailing list