Objective-C中的字符串比较
Objective-C中,NSString的==操作符比较的是字符串地址,不是字符串内容,如果需要比较内容则需要使用isEqualToString:方法。具体的介绍可以看这里. 但是Xcode会对部分字符串做优化,相同的字符串会使用同一份拷贝,所以有时候也会出现意想不到的“正确”结果,比如:[*]NSString *str1 = @"Homebrew";
[*]NSString *str2 = @"Homebrew";
[*]
[*]// This compares the addresses of the string
[*]if (str1 == str2)
[*]NSLog (@"str1 equals str2");
[*]else
[*]NSLog (@"str1 does not equal str2");
这段代码会打印出 str1 equals str2,但是这样就不会:
[*]// Create a C string
[*]char *cStr = "Homebrew";
[*]NSString *str3 = ;
[*]NSString *str4 = @"Homebrew";
[*]
[*]// Wrong - this compares the address of the string
[*]if (str3 == str4)
[*]NSLog (@"str3 equals str4");
[*]else
[*]NSLog (@"str3 does not equal str4");
另外,正确的字符串内容比较方法为:
[*]char *cStr = "Homebrew"; NSString *str3 = ; NSString *str4 = @"Homebrew"; if () NSLog (@"str3 equals str4"); else NSLog (@"str3 does not equal str4");
原文地址:http://all-ipad.net/string-compare-in-objective-c/?utm_source=rss&utm_medium=rss&utm_campaign=string-compare-in-objective-c
【编辑推荐】
[*]详谈Objective-C内存管理机制
[*]Xcode中使用Objective-C基础语法学习教程
[*]解析Objective-C中多态、动态类型和动态绑定
[*]Objective-C学习文档之协议使用方法
[*]SQLite3中针对Objective-C的持久层框架
页:
[1]