rectifiedIndexOf()
Basile B.
b2.temp at gmx.com
Sat May 6 06:07:23 UTC 2023
On Friday, 5 May 2023 at 16:51:25 UTC, apz28 wrote:
> On Friday, 5 May 2023 at 14:50:45 UTC, Salih Dincer wrote:
>> 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`.
>>
> Or as below
>
> struct IndexOfResult
> {
> ptrdiff_t value;
> alias value this;
>
> bool opCast(T : bool)() const @nogc pure @safe
> {
> return value >= 0;
> }
> }
>
> void main()
> {
> import std.string : indexOf;
> import std.stdio : writeln, writefln;
>
> enum chr = 'a';
> enum arr = "dlang";
> if (auto res = IndexOfResult(arr.indexOf(chr)))
> {
> assert(arr[res] == chr);
> res.writefln!"[ --> %s ]";
> }
> else
> writeln("Not found!");
> }
Yeah IndexOfResult is a much better name... but you should not
change the comparison operator... in theory using `!=-1` allows
`-2`, ie `size_t.max-1` to be a valid result.
More information about the Digitalmars-d
mailing list