Why isn't strfind written to return a value in all cases?
7 views (last 30 days)
A very common programming question (e.g. logical expression failure ) occurs because strfind's behavior when no match is found is to return "" . Since anytime strfind reports success, the output is 1 or more positive integers, why doesn't strfind return zero (equivalent to logical false) on failure? That seems much more intuitive (at least to me), and it saves the pain of writing " if length(strfind()) " .
Stephen23 on 8 Jan 2016
Edited: Stephen23 on 9 Jan 2016
What you are proposing breaks a basic property of strfind (and find, etc): the number of elements in the output is equal to the number of detected patterns. If a user only needs to know how many times that pattern exists:
will no longer work following your proposal. It would then require a special case for the length of the output, i.e. one that would need to be dealt with separately in all code. Consider looping over the found indices:
for k = strfind(str,pat)
This loop iterates as many times as there are output indices. So if pat is not matched, then the loop (correctly) iterates zero times. And if the output instead would be zero it requires an uncomfortable special-case handling (either if inside the loop, or some ugly zero-removal in the loop variable definition).
To be consistent your proposal would also have to applied to find as well, as well as every other function that returns indices. Can you imagine the confusion?
Why is 0 as an output better than ? The only difference would be those students would get some different error messages (something about indices being non-zero) and get equally confused. The required test (if no pattern found):
is hardly simpler than the one required now:
Usually I write my "no-string-found" case first, to make it obvious:
idx = strfind(..);