不区分大小写的字符串比较 [英] Case insensitive compare against bunch of strings

查看:161
本文介绍了不区分大小写的字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将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.

推荐答案

p>

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.

例如,如果你对一个常量bunchOfStrings做了很多检查,你可以使用 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]];
}

这篇关于不区分大小写的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆