On 07/29/2010 07:05 AM, Nick Sabalausky wrote:
"Nick Sabalausky"<[email protected]>  wrote in message
news:[email protected]...
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];

Reply via email to