Why Don't We Use == To Compare Strings In Matlab

后端 未结 3 1032
深忆病人
深忆病人 2020-12-20 17:31

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 =

相关标签:
3条回答
  • 2020-12-20 18:24

    Another small exception is with empty strings.

    Using '' == '' in if statement evaluates to false.

    strcmp('','') is true.

    0 讨论(0)
  • 2020-12-20 18:29

    == uses character-by-character comparison, so trying to test for equality with == with two strings of different lengths should give you an error.

    0 讨论(0)
  • 2020-12-20 18:35

    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).

    0 讨论(0)
提交回复
热议问题