I am trying to trim a phone number and using the following code but it does not trim whitespace or the '-'. I need to erase all chars except those in the character set given
func trimmedNumber(s : String)->String
{
let characterSet = NSCharacterSet(charactersInString: "+*#0123456789")
let trimmedString = s.stringByTrimmingCharactersInSet(characterSet.invertedSet)
return trimmedString
}
To remove specific set of characters from a String in Swift, take these characters to be removed in a set, and call the removeAll(where:) method on this string str , with the predicate that if the specific characters contain this character in the String.
Removing the specific character To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.
To remove last character of a String in Swift, call removeLast() method on this string. String. removeLast() method removes the last character from the String.
Overview. A CharacterSet represents a set of Unicode-compliant characters. Foundation types use CharacterSet to group characters together for searching operations, so that they can find any of a particular set of characters during a search.
Swift 3/4:
let set = CharacterSet(charactersIn: "+*#0123456789")
let stripped = s.components(separatedBy: set.inverted).joined()
func trimmedNumber(s : String) -> String {
let characterSet = Set("+*#0123456789".characters)
return String(s.characters.lazy.filter(characterSet.contains))
}
Or in Swift 1:
func trimmedNumber(s : String) -> String {
let characterSet = Set("+*#0123456789")
return String(lazy(s).filter { characterSet.contains($0) })
}
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