在Matlab中比较字符串

在Matlab中比较字符串

本文介绍了我们为什么不使用==在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:

我能想到的所有玩具示例似乎都可以解决.

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中比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:54