Kevin Science
Kevin Science

Reputation: 303

How to remove numbers from a String in Swift

I have a String like "75003 Paris, France" or "Syracuse, NY 13205, USA".

I want to use the same code to remove all those numbers out of those Strings.

With expected output is "Paris, France" or "Syracuse, NY, USA".

How can I achieve that?

Upvotes: 13

Views: 6360

Answers (1)

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

You can do it with the NSCharacterSet

var str = "75003 Paris, France"

var stringWithoutDigit = (str.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet()) as NSArray).componentsJoinedByString("")

println(stringWithoutDigit)

Output :

Paris, France

Taken reference from : https://stackoverflow.com/a/1426819/3202193

Swift 4.x:

let str = "75003 Paris, France"

let stringWithoutDigit = (str.components(separatedBy: CharacterSet.decimalDigits)).joined(separator: "")

print(stringWithoutDigit)

Upvotes: 27

Related Questions