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

后端 未结 3 1039
深忆病人
深忆病人 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: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).

提交回复
热议问题