我们为什么不使用==在Matlab中比较字符串 [英] Why Don't We Use == To Compare Strings In Matlab

查看:71
本文介绍了我们为什么不使用==在Matlab中比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,普遍认为使用strcmp是比较字符串的正确方法,但是我的问题是为什么?根据帮助:

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在A和B之间进行逐元素比较 并返回元素大小设置为逻辑1的相同大小的矩阵 关系为真且元素设置为逻辑0的地方 不是.

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.

推荐答案

strcmp还会检查输入内容是否为char类,例如,strcmp('a',double('a'))返回false,但是'a' == double('a')返回true. strcmp干净地处理空输入,您不必担心两个字符串的长度相同.而且,您可以使用单元格输入轻松地比较多个字符串,这很有用.

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.

字符串比较可能会慢很多-至少在当前的Matlab中.但是,不要以可读性和可维护性为代价过早地优化代码.仅在极少数确实需要性能并且非常确定要比较的内容(例如,首先使用ischarisempty)的情况下,才使用==(或也许是isequal).

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

这篇关于我们为什么不使用==在Matlab中比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆