与一堆字符串进行不区分大小写的比较

发布于 2024-09-09 03:27:38 字数 76 浏览 2 评论 0 原文

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时浪漫 2024-09-16 03:27:38

这是一个小辅助函数:

BOOL isContainedIn(NSArray* bunchOfStrings, NSString* stringToCheck)
{
    for (NSString* string in bunchOfStrings) {
        if ([string caseInsensitiveCompare:stringToCheck] == NSOrderedSame)
            return YES;
    }
    return NO;
}

当然,这可以针对不同的用例进行极大的优化。

例如,如果您对常量的 chunkOfStrings 进行大量检查,则可以使用 NSSet 来保存字符串的小写版本并使用 containsObject:

BOOL isContainedIn(NSSet* bunchOfLowercaseStrings, NSString* stringToCheck)
{
    return [bunchOfLowercaseStrings containsObject:[stringToCheck lowercaseString]];
}

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]];
}
裂开嘴轻声笑有多痛 2024-09-16 03:27:38

只需对 Nikolai 的答案添加一些补充:

NSOrderedSame 被定义为 0

typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};

因此,如果您在 nil 对象上调用 caseInsensitiveCompare: ,您将得到 <代码>零。然后,将 nilNSOrderSame (即 0)进行比较,您会得到一个匹配,这当然是错误的。

此外,您还必须检查传递给 caseInsensitiveCompare: 的参数是否必须不为零。来自文档

该值不能为零。如果该值为 nil,则行为为
未定义,并且可能在 OS X 的未来版本中更改。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文