indexOf's return val upon not found

Pelle pelle.mansson at gmail.com
Thu Jul 29 02:43:13 PDT 2010


On 07/29/2010 07:05 AM, Nick Sabalausky wrote:
> "Nick Sabalausky"<a at a.a>  wrote in message
> news:i2r1nt$1egu$1 at digitalmars.com...
>> Wouldn't it be better if std.string's indexOf/lastIndexOf returned
>> haystack.length instead of -1 to indicate "not found"? The -1 is never
>> really useful, but needs like this are fairly common:
>>
>> auto slice = str[str.indexOf(needle)..$];
>>
>> Which gives you an empty string if needle doesn't exist, which I find is
>> usually exactly what I want anyway (and consistent with find's semantics,
>> IIRC). But with the current semantics of indexOf/lastIndexOf, the risk of
>> the occasional -1 forces the clean code above to be turned into something
>> like this:
>>
>> auto needleIndex = str.indexOf(needle);
>> auto slice = needleIndex==-1? "" : str[needleIndex..$];
>>
>> Yuck.
>>
>
> Another case where indexOf is currently awkward is if you want a slice of
> str that strips off everything up until the first of a few possiblities. If
> indexOf returned haystack.length upon not found, you could just do something
> like this:
>
> auto startIndex = min(str.indexOf("a"), str.indexOf("b"), str.indexOf("c"));
> auto slice = str[startIndex..$];
>
> With the current indexOf, the correct code is, well, quite a bit messier.
> And this is one case where find doesn't provide quite as nice of a solution
> either (unlike my first example which could probably be replaced entirely by
> find).
>
>

auto slice = str.find("a", "b", "c").field[0];


More information about the Digitalmars-d mailing list