Case insensitive compare against bunch of strings

2020-06-28 03:25发布

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.

2条回答
Anthone
2楼-- · 2020-06-28 04:04

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]];
}
查看更多
老娘就宠你
3楼-- · 2020-06-28 04:08

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.

查看更多
登录 后发表回答