Case insensitive comparison NSString Case insensitive comparison NSString ios ios

Case insensitive comparison NSString


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

The documentation is located at Search and Comparison Methods


 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 }


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.