问题
I know it's commonly accepted that using strcmp
is the proper way to compare strings, but my question is why? According to the help:
A == B does element by element comparisons between A and B and returns a matrix of the same size with elements set to logical 1 where the relation is true and elements set to logical 0 where it is not.
And all the toy examples I can come up with seem to work out.
回答1:
strcmp
also checks that the inputs are class char, e.g., strcmp('a',double('a'))
returns false, but 'a' == double('a')
returns true. strcmp
cleanly handles empty inputs and you don't have to worry about the two strings being the same length either. And you can use cell inputs to easily compare multiple strings which is useful.
String comparisons can be a good deal slower - at least in current Matlab. But don't prematurely optimize your code at the cost of readability and maintainability. Only use ==
(or maybe isequal
) in rare cases when you really do need performance and are very very sure about what you're comparing (use ischar
and isempty
first, for example).
回答2:
==
uses character-by-character comparison, so trying to test for equality with ==
with two strings of different lengths should give you an error.
回答3:
Another small exception is with empty strings.
Using '' == ''
in if statement evaluates to false.
strcmp('','')
is true.
来源:https://stackoverflow.com/questions/19164217/why-dont-we-use-to-compare-strings-in-matlab