std.algorithm.strip functionality

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed May 7 01:40:33 UTC 2025


On Tuesday, May 6, 2025 3:19:29 PM Mountain Daylight Time Pete Padil via Digitalmars-d-learn wrote:
> I compiled and ran the following test program:
> ```d
> import std.stdio, std.algorithm;
>
> void main()
> {
>     long[] a = [1, 2, 3, 15, 4];
>     auto b = a[].strip(15);
>     writeln(a);
>     writeln(b);
> }
> ```
> I get:
> [1, 2, 3, 15, 4]
> [1, 2, 3, 15, 4]
> It did not remove 15, it does work if 15 is at the beginning or
> end.
> Is this a bug or am I misunderstading the docs?
>
> version:   1.41.0-beta1 (DMD v2.111.0, LLVM 19.1.7)
>
> thanks

strip removes the requested elements from the ends (whereas stripLeft does
it from the front of the range, and stripRight does it from the back of the
range). It's a generalization of the strip function which strips whitespace
from both ends (what some languages call trim).

If you want to remove an element from the middle, then
std.algorithm.iteration.filter will return a lazy range which filters
elements based on the predicate - e.g.

auto result = range.filter!(a=> a != 15)();

and if you want an array instead of a lazy range, you can allocate a new one
with std.array.array, e.g.

auto result = range.filter!(a=> a != 15)().array();

Alternatively, std.algorithm.mutation.remove can be used to remove an
element at a specific index (shifting all of the other elements after it in
the array), but then you'll need to use a function such as
std.algorithm.searching.find or std.algorithm.countUntil to get the
element's offset to pass to remove.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list