pgrueda
pgrueda

Reputation: 51

Swift 3 Trimming characters

Anyone know how to Trim or eliminate characters from string? I have a data from UIlabel like "ABCDE1000001" and I need to get the numbers only. Any idea? trimming? concat? any other solution?

I also try this but looking for other solution

 let cardtrim = String.trimmingCharacters(in: CharacterSet(charactersIn: "ABCDEF"))

Upvotes: 3

Views: 10212

Answers (5)

vadian
vadian

Reputation: 285072

Consider that trimmingCharacters removes only (consecutive) leading or trailing characters which match the character set.

To remove all non-numeric characters in a string I recommend regular expression

let string = "ABC12DE100YU0001"
let trimmedString = string.replacingOccurrences(of: "\\D", with: "", options: .regularExpression)
// -> "121000001"

Update:

In Swift 5+ there is a more efficient way:

let string = "ABC12DE100YU0001"
var trimmedString = string
trimmedString.removeAll{ !$0.isNumber }
// -> "121000001"

Upvotes: 2

Dominik Bucher
Dominik Bucher

Reputation: 2169

You gotta get Swifty:

let string = "ABC12DE100YU0001".filter { ("0"..."9").contains($0) }

In extension:

extension String {

    func filterLetters() -> String {
        return filter { ("0"..."9").contains($0) }
    }
}

Upvotes: 2

Rashwan L
Rashwan L

Reputation: 38833

Try this instead of hardcoding the charactersIn, this is a dynamic solution that will work on other variations of strings than just ABCDEF.

extension String {

    var numbersOnly: String {

        let numbers = self.replacingOccurrences(
             of: "[^0-9]",
             with: "",
             options: .regularExpression,
             range:nil)
        return numbers
    }
}

let string = "A77BC66DE1001".numbersOnly // 77661001

Upvotes: 3

Siyavash
Siyavash

Reputation: 980

This extension will return the digits in a string which is exactly what you need

extension String {

    var digits: String {
        return components(separatedBy: CharacterSet.decimalDigits.inverted)
            .joined()
    }
}

Source

Upvotes: -1

David Pasztor
David Pasztor

Reputation: 54716

Your code works perfectly, but you need to call it on the String variable in which you store the value you want to trim.

let stringToTrim = "ABCDE1000001"
let cardtrim = stringToTrim.trimmingCharacters(in: CharacterSet(charactersIn: "ABCDEF")) //value: 1000001

A more generic solution is to use CharacterSet.decimalDigits.inverted to only keep the digits from the String.

let cardtrim = stringToTrim.trimmingCharacters(in: CharacterSet.decimalDigits.inverted)

Be aware that trimmingCharacters only removes the characters in the characterset from the beginning and end of the String, so if you have a String like ABC101A101 and want to remove all letters from it, you'll have to use a different approach (for instance regular expressions).

Upvotes: 6

Related Questions