比较字符时,ischar(x)&& x =='b'等同于strcmp(x,'b')? [英] When comparing characters, is ischar(x) && x == 'b' equivalent to strcmp(x, 'b')?

查看:131
本文介绍了比较字符时,ischar(x)&& x =='b'等同于strcmp(x,'b')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MATLAB中,我经常使用它来检查变量是否包含某个单个字符:

In MATLAB, I often use this to check if a variable contains a certain single character:

if ischar(x) && x == 'b'

为减少混乱,我正在考虑将其更改为:

to reduce clutter I'm thinking of changing it to this:

if strcmp(x, 'b')

因为如果x不是字符或不等同于'b',则比较将返回false(如您期望的那样).在这种情况下,这些语句是等效的还是存在陷阱?

because if x isn't a character or isn't equivalent to 'b', the comparison returns false as you would expect. Are these statements equivalent in this case or are there gotchas?

更多信息:x == 'b'是不够的,因为当x == 98时它返回true,但是在某些情况下(例如验证用户输入),98可能是无效的输入,而b 有效输入.另外,如果x不是标准数据类型(例如,如果是对象),则第一个失败.举这个(愚蠢的)例子:

More info: x == 'b' isn't enough because this returns true when x == 98, but in certain cases (like validating user input), 98 may be invalid input while b is valid input. Also, the first one fails if x isn't a standard data type (if it's an object for example). Take this (stupid) example:

x = table();
x == 'b'

这将引发错误,因为未为表定义eq,但是strcmp(x, 'b')返回0是因为strcmp似乎也在执行类型检查.不过,是否需要这种异常处理可能取决于情况.

This throws an error because eq isn't defined for tables, but strcmp(x, 'b') returns 0 because it appears that strcmp also performs a type check. Whether or not this exception handling is desirable probably depends on the circumstances though.

推荐答案

是必经之路. == 运算符是元素级的.如果x不是单个字符,则测试将返回logical数组而不是一个:

strcmp is the way to go. The == operator is element-wise. If x is not a single character, then the test returns a logical array instead of one:

>> x = 'abc';
>> x == 'b'
ans =
     0     1     0
>> x = 'bbb';
>> x == 'b'
ans =
     1     1     1

两者都不相等,第二个满足if语句.

Neither are equal, the second one satisfies the if statement.

还要注意,在==时( eq )以元素为单位, isequal 测试对象是否相等.请注意,在测试中isequal不会不考虑数据类型.那是:

Also note that while == (eq) is element-wise, isequal tests for object equality. The caveat is that isequal does not consider data type in the test. That is:

>> isequal('abc',[97 98 99])
ans =
     1
>> strcmp('abc',[97 98 99])
ans =
     0
>> eq('abc',[97 98 99])
ans =
     1     1     1

如果您关心数据类型,请使用strcmp,否则请使用isequal.

If you care about data type, use strcmp, if not, use isequal.

还考虑使用 strcmpi 忽略大小写或 strncmp 来比较第一个N元素.

这篇关于比较字符时,ischar(x)&& x =='b'等同于strcmp(x,'b')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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