Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
Kevin Science Avatar asked Jul 10 '15 02:07

Kevin Science


People also ask

How do I remove a number from a string in Swift?

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.

How do I remove special characters from a string 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 filter a string in Swift?

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.


1 Answers

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)
like image 55
Ashish Kakkad Avatar answered Oct 04 '22 21:10

Ashish Kakkad