Case insensitive compare against bunch of strings

梦想的初衷 提交于 2019-12-05 04:32:01

问题


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.



来源:https://stackoverflow.com/questions/3222284/case-insensitive-compare-against-bunch-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!