Case insensitive compare against bunch of strings(与一堆字符串比较不区分大小写)
问题描述
将 NSString 与其他不区分大小写的字符串进行比较的最佳方法是什么?如果它是字符串之一,则该方法应返回 YES,否则返回 NO.
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.
推荐答案
这里有个小辅助函数:
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.
例如,如果您对常量 bundleOfStrings 进行大量检查,您可以使用 NSSet
来保存字符串的小写版本并使用 containsObject:
:
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]];
}
这篇关于与一堆字符串比较不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!