Manipulate slice or specific element of range and return range
Timoses
timosesu at gmail.com
Wed Mar 21 17:04:34 UTC 2018
On Wednesday, 21 March 2018 at 12:53:56 UTC, Ali Çehreli wrote:
>
> Here is another one that uses ForwardRange.
>
> import std.range; // empty, take, save, chain, popFrontN;
> import std.uni; // asLowerCase;
> import std.algorithm; // equal, filter;
> import std.conv; // text;
>
> auto initialLowerCased(R)(R str, size_t N = 1) {
> if (str.empty) {
> N = 0;
> }
> auto frontPart = str.take(N);
> auto rest = str.save;
> rest.popFrontN(N);
>
> return chain(frontPart.asLowerCase, rest);
> }
>
> unittest {
> assert(initialLowerCased("My Test String", 4).equal("my
> test String"));
> assert(initialLowerCased("").equal(""));
> }
>
> auto foo(R)(R str) {
> return str.filter!(c => c != ' ').initialLowerCased;
> }
>
> void main() {
> auto result = foo("My Capital String");
> // result above is a range. std.conv.text can make a string:
> string lower = result.text;
> assert(lower == "myCapitalString");
> }
>
> Ali
I like it! I remember having a similar situation another time
where it was not about strings. I wonder why there is no method
for this in the standard library that can execute a predicate on
specific elements of a range..
More information about the Digitalmars-d-learn
mailing list