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.
Swift String contains() The contains() method checks whether the specified string (sequence of characters) is present in the string or not.
While the find and count string methods can check for substring occurrences, there is no ready-made function to check for the occurrence in a string of a set of characters. While working on a condition to check whether a string contained the special characters used in the glob.
The Java String contains() method is used to check whether the specific set of characters are part of the given string or not. It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise. It can be directly used inside the if statement.
Add this Swift extension so that all instances of Character class have two new functions: isUpperCase() to test if the character is upper case and isLowerCase() to test if the character is lower case.
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") }
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:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With