开发者

String comparison in Objective-C

开发者 https://www.devze.com 2022-12-26 14:03 出处:网络
I\'ve currently got a webserver set up which I communicate over SOAP with my iPhone app. I am returning a NSString containing a GUID and when I attempt to compare this with another NSString I get some

I've currently got a webserver set up which I communicate over SOAP with my iPhone app. I am returning a NSString containing a GUID and when I attempt to compare this with another NSString I get some strange results.

Why would this not fire? Surely the two strings ar开发者_JAVA技巧e a match?

NSString *myString = @"hello world";

if (myString == @"hello world")
    return;


Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}


You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:

if ([category isEqualToString:@"Some String"])
{
   // Both strings are equal without respect to their case.
}

Case-insensitive is like this:

if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
   // Both strings are equal with respect to their case.
}


You can compare string with below functions.

NSString *first = @"abc";
NSString *second = @"abc";
NSString *third = [[NSString alloc] initWithString:@"abc"];
NSLog(@"%d", (second == third))  
NSLog(@"%d", (first == second)); 
NSLog(@"%d", [first isEqualToString:second]); 
NSLog(@"%d", [first isEqualToString:third]); 

Output will be :-
    0
    1
    1
    1
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号