rectifiedIndexOf()

Salih Dincer salihdb at hotmail.com
Fri May 5 14:50:45 UTC 2023


On Friday, 5 May 2023 at 02:43:15 UTC, Basile B. wrote:
> As often in D you can use a struct to help...
> `opCast` is used for the `if` condition and the original value 
> for reading back in the array, via `alias this`.

I haven't seen such an accurate solution from those who replied 
to me until now. Thanks a lot because very works!

```d
auto toBool(ptrdiff_t t)
{
   struct ToBool
   {
     ptrdiff_t value;

     alias value this;

     bool opCast(T : bool)()
     {
       return value != -1;
     }
   }
   return ToBool(t);
}

void find(char chr)
{
   import std.stdio, std.range,
          std.string : indexOf;

   if(auto res = arr.indexOf(chr).toBool)
   {
     arr.writeln;
     assert(arr[res] == chr);
     ' '.repeat(res).writeln("^--found!");
   } else {
     chr.writeln(" character not found!");
   }
}

auto arr = "dlang".dup;

void main()
{
   foreach(chr; "cad") chr.find();
}

/* Prints:
c character not found!
dlang
   ^--found!
dlang
^--found!
*/
```

SDB at 79




More information about the Digitalmars-d mailing list