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
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")
}
func isAnyCharacter( from charSetString: String, containedIn string: String ) -> Bool
{
return Set( charSetString.characters ).isDisjointWith( Set( string.characters) ) == false
}
Swift 3 example:
extension String{
var isContainsLetters : Bool{
let letters = CharacterSet.letters
return self.rangeOfCharacter(from: letters) != nil
}
}
Usage :
"123".isContainsLetters // false
From Swift 1.2 you can do that using Set
var str = "Hello, World!"
let charset: Set<Character> = ["e", "n"]
charset.isSubsetOf(str) // `true` if `str` contains all characters in `charset`
charset.isDisjointWith(str) // `true` if `str` does not contains any characters in `charset`
charset.intersect(str) // set of characters both `str` and `charset` contains.
Swift 3 or later
let isSubset = charset.isSubset(of: str) // `true` if `str` contains all characters in `charset`
let isDisjoint = charset.isDisjoint(with: str) // `true` if `str` does not contains any characters in `charset`
let intersection = charset.intersection(str) // set of characters both `str` and `charset` contains.
print(intersection.count) // 1
Use like this in swift 4.2
var string = "Hello, World!"
let charSet = NSCharacterSet.letters
if string.rangeOfCharacter(from:charSet)?.isEmpty == false{
print ("String contain letters");
}
swift3
var str = "Hello, playground"
let res = str.characters.contains { ["x", "z"].contains( $0 ) }