Objective-C中的字符串比较

Objective-C中,NSString的==操作符比较的是字符串地址,不是字符串内容,如果需要比较内容则需要使用isEqualToString:方法。具体的介绍可以看这里:http://iphonedevelopertips.com/cocoa/compare-nsstrings-objects.html 但是Xcode会对部分字符串做优化,相同的字符串会使用同一份拷贝,所以有时候也会出现意想不到的“正确”结果,比如:

 

1

2

3

4

5

6

7

8

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,但是这样就不会:

 

1

2

3

4

5

6

7

8

9

10

// Create a C string

char *cStr = "Homebrew";

NSString *str3 = [NSString stringWithUTF8String:cStr];

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");

 

另外,正确的字符串内容比较方法为:

 

1

2

3

4

5

6

7

8

char *cStr = "Homebrew";

NSString *str3 = [NSString stringWithUTF8String:cStr];

NSString *str4 = @"Homebrew";

 

if ([str3 isEqualToString:str4])

  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中的字符串比较)