确定字符串是否包含 Swift 集合中的字符的最佳方法是什么 [英] What is the best way to determine if a string contains a character from a set in Swift

查看:29
本文介绍了确定字符串是否包含 Swift 集合中的字符的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定一个字符串是否包含我定义的自定义集中的任何字符.

I need to determine if a string contains any of the characters from a custom set that I have defined.

我从这个 发布您可以使用 rangeOfString 来确定一个字符串是否包含另一个字符串.当然,如果您一次测试一个字符,这也适用于字符.

I see from this post that you can use rangeOfString to determine if a string contains another string. This, of course, also works for characters if you test each character one at a time.

我想知道这样做的最佳方法是什么.

I'm wondering what the best way to do this is.

推荐答案

您可以创建包含自定义字符集的 CharacterSet然后针对这个字符集测试成员资格:

You can create a CharacterSet containing the set of your custom characters and then test the membership against this character set:

Swift 3:

let charset = CharacterSet(charactersIn: "aw")
if str.rangeOfCharacter(from: charset) != nil {
    print("yes")
}

对于不区分大小写的比较,使用

For case-insensitive comparison, use

if str.lowercased().rangeOfCharacter(from: charset) != nil {
    print("yes")
}

(假设字符集只包含小写字母).

(assuming that the character set contains only lowercase letters).

Swift 2:

let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset) != nil {
    print("yes")
}

Swift 1.2

let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset, options: nil, range: nil) != nil {
    println("yes")
}

这篇关于确定字符串是否包含 Swift 集合中的字符的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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