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?
In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.
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.
To filter strings in a Swift String Array based on length, call filter() method on this String Array, and pass the condition prepared with the string length as argument to the filter() method. filter() method returns an array with only those elements that satisfy the given predicate/condition.
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)
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