std.string and std.algorithm: what to do?

grauzone none at example.net
Thu May 14 23:03:04 PDT 2009


Andrei Alexandrescu wrote:
> Daniel Keep wrote:
>>
>> Steven Schveighoffer wrote:
>>> On Thu, 14 May 2009 09:55:08 -0400, Andrei Alexandrescu
>>> <SeeWebsiteForEmail at erdani.org> wrote:
>>>
>>>> Also, I dislike the signature int find() that returns -1 if not found.
>>>> Time and again experience shows that find() returning a range is much
>>>> better in real code because it works seamlessly when the
>>>> substring/element was not found (no more need for an extra test!)
>>> Ech, returning -1 is the bane of Java and C#.  The return value should
>>> be the end of the string, regardless of whether it is a range or 
>>> index. I could never understand the mentality of returning -1 versus 
>>> end of
>>> string.
>>>
>>> -Steve
>>
>> int idx = find(str);
>> if( idx == -1 ) doStuff;
>>
>> - or -
>>
>> if( idx == str.length ) doStuff;
> 
> I think Steve's point is that often you want to do something like:
> 
> auto before = str[0 .. find(str, something)];
> 
> or
> 
> auto after = str[find(str, something) .. $];
> 
> which behave nicely at limit conditions (when something isn't found). In 
> contrast, the version with -1 needs a separate varible and a test - a mess.

But most time, you want to know both _if_ something was found, and 
where. Returning the length of the string makes checking if something 
was found harder. That's also quite a mess.

Maybe a good way would be to return a pair of slices, before and after 
something was found (ignoring that there are no MRVs):

(char[], char[]) myfind(char[] str, char[] tofind) {
	int index = find(str, tofind); //returns str.length if not found
	return str[0..index], str[index..$];
}

This would give the user lots of flexibility, without having to declare 
useless temporaries, especially not for the first argument passed to 
myfind().

For example: was something found?
bool found = myfind(bla, blubb)[1].length;

(That's still more elegant than to compare lengths.)

> 
> Andrei



More information about the Digitalmars-d mailing list