开发者

Case insensitive compare against bunch of strings

开发者 https://www.devze.com 2023-01-07 04:42 出处:网络
What would be the best method to compare an NSString to a bunch of other strings case insensitive? If it is o开发者_开发百科ne of the strings then the method should return YES, otherwise NO.Here\'s a

What would be the best method to compare an NSString to a bunch of other strings case insensitive? If it is o开发者_开发百科ne of the strings then the method should return YES, otherwise NO.


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]];
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消