How to extend the string class to return this inside the square bracket?

Ali Çehreli acehreli at yahoo.com
Fri Aug 13 23:21:42 UTC 2021


On 8/13/21 4:08 PM, jfondren wrote:
> On Friday, 13 August 2021 at 22:09:59 UTC, Marcone wrote:
>>
>> Isn't there some unario operator template that I can use with lambda 
>> to handle a string literal?
> 
> So, something other than an exact "lit"[0..this.xx(..)] syntax is fine?
> 
> What didn't you like about `"Hello World!".findSplit("o")[0].writeln;` 
> then?
> 
> What is a real example of something you want to do?

And I started writing the following but stopped because the semantics 
are not clear. I first called it 'between' but then should the 'o' that 
was searched be a part of the output?

Should "from 'o' to 'o'" produce an empty string, should it include a 
single 'o' or should it go all the way to the next 'o'?

What about the last line which says "from 'd' to 'a'"? Is that an 
entirely empty range or just 'd' or 'd' till the end?

I don't think the programming language can decide one way or the other.

import std.algorithm;
import std.range;
import std.stdio;

auto inclusive(R, E)(R range, E fromNeedle, E toNeedle) {
   auto found = range.find(fromNeedle);
   return chain(found.front.only, 
found.drop(1).findSplitAfter(only(toNeedle))[0]);
}

void main() {
   const s = "Hello World!";
   auto r = s.inclusive('o', 'o');
   writeln(r);

   writeln("abcdef".inclusive('d', 'a'));
}

Ali


More information about the Digitalmars-d-learn mailing list