Case insensitive compare against bunch of strings

2020-06-28 03:36发布

问题:

What would be the best method to compare an NSString to a bunch of other strings case insensitive? If it is one of the strings then the method should return YES, otherwise NO.

回答1:

Here's a little helper function:

BOOL isContainedIn(NSArray* bunchOfStrings, NSString* stringToCheck)
{
    for (NSString* string in bunchOfStrings) {
        if ([string caseInsensitiveCompare:stringToCheck] == NSOrderedSame)
            return YES;
    }
    return NO;
}

Of course this could be greatly optimized for different use cases.

If, for example, you make a lot of checks against a constant bunchOfStrings you could use an NSSet to hold lower case versions of the strings and use containsObject::

BOOL isContainedIn(NSSet* bunchOfLowercaseStrings, NSString* stringToCheck)
{
    return [bunchOfLowercaseStrings containsObject:[stringToCheck lowercaseString]];
}


回答2:

Just to add a few additions to Nikolai's answer:

NSOrderedSame is defined as 0

typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};

So if you call caseInsensitiveCompare: on a nil object you would get nil. Then you compare nil with NSOrderSame (which is 0) you would get a match which of course is wrong.

Also you will have to check if parameter passed to caseInsensitiveCompare: has to be not nil. From the documentation:

This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of OS X.