What is the best way to determine if a string contains a character from a set in Swift
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 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.
Solution 1:
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")
}
Solution 2:
ONE LINE Swift4 solution to check if contains letters:
CharacterSet.letters.isSuperset(of: CharacterSet(charactersIn: myString) // returns BOOL
Another case when you need to validate string for custom char sets. For example if string contains only letters and (for example) dashes and spaces:
let customSet: CharacterSet = [" ", "-"]
let finalSet = CharacterSet.letters.union(customSet)
finalSet.isSuperset(of: CharacterSet(charactersIn: myString)) // BOOL
Hope it helps someone one day:)
Solution 3:
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
Solution 4:
Swift 3 example:
extension String{
var isContainsLetters : Bool{
let letters = CharacterSet.letters
return self.rangeOfCharacter(from: letters) != nil
}
}
Usage :
"123".isContainsLetters // false