Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all chars except those in CharacterSet in Swift

Tags:

ios

swift

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
}
like image 692
tech74 Avatar asked Aug 28 '15 11:08

tech74


People also ask

How do I ignore special characters in Swift?

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.

How do I remove a specific character from a string in Swift?

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.

How do you remove the last two characters in Swift?

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.

What is CharacterSet in Swift?

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.


2 Answers

Swift 3/4:

let set = CharacterSet(charactersIn: "+*#0123456789")
let stripped = s.components(separatedBy: set.inverted).joined()
like image 126
dalton_c Avatar answered Sep 17 '22 19:09

dalton_c


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) })
}
like image 24
oisdk Avatar answered Sep 17 '22 19:09

oisdk