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)
Converting Jason Coco's answer to Swift for the profoundly lazy :)
if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
{
// Strings are equal.
}
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
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
}
On macOS you can simply use -[NSString isCaseInsensitiveLike:]
, which returns BOOL
just like -isEqual:
.
if ([@"Test" isCaseInsensitiveLike: @"test"])
// Success
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()){
}
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.