What is the best way to determine if a string contains a character from a set in Swift

前端 未结 11 1710
南旧
南旧 2020-11-30 01:03

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

I see from this post that you can use rangeOfString to determine

11条回答
  •  攒了一身酷
    2020-11-30 01:35

    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")
    }
    

提交回复
热议问题