Why isn't strfind written to return a value in all cases?

7 次查看(过去 30 天)
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()) " .

回答(1 个)

Stephen23
Stephen23 2016-1-8
编辑:Stephen23 2016-1-9
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:
numel(strfind(str,pat))
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)
fun(k);
end
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):
idx>0
is hardly simpler than the one required now:
~isempty(idx)
Usually I write my "no-string-found" case first, to make it obvious:
idx = strfind(..);
if isempty(idx)
...
else
...
end
  2 个评论
Carl Witthoft
Carl Witthoft 2016-1-8
I suppose there's no universally optimal answer. My preference is that functions return an error message or error value(s) when they're unsuccessful; clearly other folks prefer a "null" or "empty" special value to be returned.
Walter Roberson
Walter Roberson 2016-1-8
The function is not unsuccessful. The function returns a list of all of the matches. 1 entry for 1 match, 2 entries for 2 matches, 0 entries for 0 matches...

请先登录,再进行评论。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by