250

Can anyone point me to any resources about case insensitive comparison in Objective C? It doesn't seem to have an equivalent method to str1.equalsIgnoreCase(str2)

Arun_
  • 1,806
  • 2
  • 20
  • 40
Tejaswi Yerukalapudi
  • 8,987
  • 12
  • 60
  • 101

12 Answers12

573
if( [@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
  // strings are equal except for possibly case
}

The documentation is located at Search and Comparison Methods

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jason Coco
  • 77,985
  • 20
  • 184
  • 180
  • 157
    It is worth mentioning that in case when `@"Some String"` is received from any other call and happens to be `nil`, your `if` will give `true` as sending `caseInsensitiveCompare` to `nil` is valid and results in another `nil` which, in our case, compared with `NSOrderedSame` will return `true` (`NSOrderedSame` is defined as 0). This can be a source of quite devastating bugs, as it was in my case. Cheers! – matm Mar 28 '11 at 09:22
  • 10
    My workaround for this is to implement that comparison as a method inside a category on `NSString` that returns a boolean. Then if the receiving string is `nil`, the method as a whole returns `NO`. – Defragged Feb 13 '13 at 15:38
54
 NSString *stringA;
 NSString *stringB;

 if (stringA && [stringA caseInsensitiveCompare:stringB] == NSOrderedSame) {
     // match
 }

Note: stringA && is required because when stringA is nil:

 stringA = nil;
 [stringA caseInsensitiveCompare:stringB] // return 0

and so happens NSOrderedSame is also defined as 0.

The following example is a typical pitfall:

 NSString *rank = [[NSUserDefaults standardUserDefaults] stringForKey:@"Rank"];
 if ([rank caseInsensitiveCompare:@"MANAGER"] == NSOrderedSame) {
     // what happens if "Rank" is not found in standardUserDefaults
 }
ohho
  • 50,879
  • 75
  • 256
  • 383
46

An alternative if you want more control than just case insensitivity is:

[someString compare:otherString options:NSCaseInsensitiveSearch];

Numeric search and diacritical insensitivity are two handy options.

drawnonward
  • 53,459
  • 16
  • 107
  • 112
  • 4
    As noted above by matm, this will return true if someString is nil. – nh32rg Jul 26 '13 at 15:28
  • @nh32rg Could'y you just make up for the false positive, by changing the if-statement to something like ```if ([someString compare:otherString options:NSCaseInsensitiveSearch] && someString.length > 0 && someString != (id)[NSNull null])``` – KingPolygon Dec 31 '14 at 01:19
  • 1
    actually, you need to write [...comapre:...] == 0, because compare return NSOrderSame (=0) if two strings are same. for, someString != (id)[NSNull null], I don't think it required, because if null, then, length is zero. I usually compare like this: if (someString.length > 0 && [someString compare:ortherString options:NSCaseIntensitiveSearch] == 0) – Tran Quan Jun 11 '15 at 07:24
23

You could always ensure they're in the same case before the comparison:

if ([[stringX uppercaseString] isEqualToString:[stringY uppercaseString]]) {
    // They're equal
}

The main benefit being you avoid the potential issue described by matm regarding comparing nil strings. You could either check the string isn't nil before doing one of the compare:options: methods, or you could be lazy (like me) and ignore the added cost of creating a new string for each comparison (which is minimal if you're only doing one or two comparisons).

0xWood
  • 1,326
  • 12
  • 15
  • 4
    Manipulating the casing for comparing is usually not a wise thing to do (e.g, the turkey test: http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html). When you have language-supported case comparison (such as `caseInsensitiveCompare`), always use that. – Ohad Schneider Nov 30 '16 at 16:02
8

A new way to do this. iOS 8

let string: NSString = "Café"
let substring: NSString = "É"

string.localizedCaseInsensitiveContainsString(substring) // true
Govind
  • 2,337
  • 33
  • 43
7
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
WhirlWind
  • 13,974
  • 3
  • 42
  • 42
6

Try this method

- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
Maulik
  • 19,348
  • 14
  • 82
  • 137
Reena
  • 845
  • 6
  • 8
6

Converting Jason Coco's answer to Swift for the profoundly lazy :)

if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
{
  // Strings are equal.
}
Tasik
  • 236
  • 6
  • 13
5

to check with the prefix as in the iPhone ContactApp

([string rangeOfString:prefixString options:NSCaseInsensitiveSearch].location == 0)

this blog was useful for me

iMeMyself
  • 1,649
  • 13
  • 28
1

Alternate solution for swift:

To make both UpperCase:

e.g:

if ("ABcd".uppercased() == "abcD".uppercased()){
}

or to make both LowerCase:

e.g:

if ("ABcd".lowercased() == "abcD".lowercased()){
}
FARAZ
  • 645
  • 7
  • 6
1

On macOS you can simply use -[NSString isCaseInsensitiveLike:], which returns BOOL just like -isEqual:.

if ([@"Test" isCaseInsensitiveLike: @"test"])
    // Success
mangerlahn
  • 4,746
  • 2
  • 26
  • 50
-3
NSMutableArray *arrSearchData;  
NSArray *data=[arrNearByData objectAtIndex:i];
NSString *strValue=[NSString stringWithFormat:@"%@", [data valueForKey:@"restName"]];
NSRange r = [strValue rangeOfString:key options:NSCaseInsensitiveSearch];

if(r.location != NSNotFound)
{
     [arrSearchData addObject:data];
}
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
abc
  • 1