Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two case insensitive strings?

i have 2 string objects containing same string but case is different,now i wanna compare them ignoring the case sensitivity,how to do that??here is the code...

#import <Foundation/Foundation.h>
void main()  
{  
    NSString *myString1 = @"mphasis";  
    NSString *myString2 = @"MPHASIS";
    if ([myString1 caseInsenstiveCompare:myString2])  
    {  
        NSLog (@"ITS EQUAL");  
    }  
    else  
    {   
        NSLog (@"ITS NOT EQUAL");  
    }  
}  
like image 359
pranay anand Avatar asked Feb 23 '11 11:02

pranay anand


2 Answers

If you look up caseInsensitiveCompare: in the docs you'll see that it returns an NSComparisonResult rather than a BOOL. Look that up in the docs and you'll see that you probably want it to be NSOrderedSame. So

if ([myString1 caseInsensitiveCompare:myString2] == NSOrderedSame)

should do the trick. Or just compare the lowercase strings like Robert suggested.

like image 62
Martin Gjaldbaek Avatar answered Oct 20 '22 19:10

Martin Gjaldbaek


Just use lowercaseString on both of the strings and then compare them as you would using a normal string equality check. It will still be O(n) so no big deal.

like image 24
Robert Massaioli Avatar answered Oct 20 '22 19:10

Robert Massaioli