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

前端 未结 11 1711
南旧
南旧 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:54

    You could do it this way:

    var string = "Hello, World!"
    
    if string.rangeOfString("W") != nil {
         println("exists")
    } else {
         println("doesn't exist")
    }
    
    // alternative: not case sensitive
    if string.lowercaseString.rangeOfString("w") != nil {
         println("exists")
    } else {
         println("doesn't exist")
    }
    

提交回复
热议问题