简体   繁体   English

如何比较字符串? (`==` 返回错误值)

[英]How to compare strings? (`==` returns wrong value)

I've got myself a piece of the iPhone SDK and been trying to make some simple apps.我给自己买了一块 iPhone SDK 并尝试制作一些简单的应用程序。 In this one, i want to compare the first character of self.label.string with the last one of ((UITextField *)sender).text .在这一个中,我想将self.label.string的第一个字符与((UITextField *)sender).text的最后一个字符进行比较。 I decided to name them self.texty and self.input , respectively.我决定将它们分别命名为self.textyself.input

I would expect this if statement returning yes to me under certain circumstances, however I can't seem to get that done.在某些情况下,我希望这个 if 语句向我返回yes ,但是我似乎无法完成。

(in my case, my self.label.string was equal to 'hello,', while my self.input ended in an 'h'.) (在我的例子中,我的self.label.string等于 'hello,',而我的self.input以 'h' 结尾。)

self.input = [NSString stringWithFormat:@"%@", [((UITextField *)sender).text substringFromIndex:[((UITextField *)sender).text length]-1]];
self.texty = [NSString stringWithFormat:@"%@", [self.label.string substringToIndex:1]];

if (self.input == self.texty) {
    return yes;
} else {
    return no;
}

String comparison is not done with == , but with one of the comparison methods of NSString .字符串比较不是用==完成的,而是用NSString 的比较方法之一

For example:例如:

if ([self.input compare:self.texty] == NSOrderedSame) {
if ([self.input isEqualToString:texty]) {
    return yes;
} else {
    return no;
}

EDIT:编辑:

Or a better version as the commenters noted:或者评论者指出的更好的版本:

return [self.input isEqualToString:texty];

If you're curious why the == operator doesn't work as expected, it's because you're actually comparing two scalar types (pointers to NSString objects) not the contents of the NSString objects themselves.如果您好奇 == 运算符为什么不能按预期工作,那是因为您实际上是在比较两个标量类型(指向 NSString 对象的指针)而不是 NSString 对象本身的内容。 As a result, it will return false unless the two compared NSStrings are actually the same instance in memory, regardless of the contents.因此,除非两个比较的 NSString 实际上是 memory 中的同一个实例,否则它将返回 false,无论内容如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM