rectifiedIndexOf()

Salih Dincer salihdb at hotmail.com
Fri May 5 00:19:01 UTC 2023


It has a traditional very beautiful function:  indexOf() but it 
has an important problem: returns -1 when it can't find 'c'...

```d
void main()
{
   enum chr = 'c';
   auto arr = "dlang".dup;
   if(auto res = arr.indexOf(chr))
   {
     assert(arr[res] == chr);
     // core.exception.ArrayIndexError
   }
}
```

When you try to solve the problem with boolean logic, res is now 
a bool.

```d
void main()
{
   enum chr = 'd';
   auto arr = "dlang".dup;
   if(auto res = arr.indexOf(chr) > -1)
   {
     assert(arr[res] == chr);
     // core.exception.AssertError
   }
}
```

We can solve this problem with an alternativeIndexOf, but we're 
sailing another problem: Rectified Index...

```d
import std.stdio;
void main()
{
   enum chr = 'c';
   auto arr = "dlang".dup;
   if(auto res = arr.rectifiedIndexOf(chr))
   {
     assert(arr[res - 1] == chr);
     res.writefln!"[ --> %s ]";
   } else writeln("Not found!");
}

auto rectifiedIndexOf(A)(A[] arr, A key)
{
   size_t i = 1;
   while(i <= arr.length)
   {
     if(arr[i - 1] == key)
     {
       return i;
     }
     else i++;
   }
   return 0;
}
```

So now that we've broken the traditional index approach, you need 
to consider this (res - 1) in your code.

SDB at 79


More information about the Digitalmars-d mailing list