3

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"))
rmaddy
  • 314,917
  • 42
  • 532
  • 579
pgrueda
  • 51
  • 1
  • 6

5 Answers5

6

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).

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 1
    This ***is not the best solution***. In different locales, you have no idea what might be in "decimal digits". For example - does it include the "." ? – Fattie Feb 03 '18 at 21:52
  • @Fattie `CharacterSet` uses Unicode specifications, so all of its subsets are locale independent AFAIK. – Dávid Pásztor Feb 03 '18 at 23:05
  • You know I really appreciate what you're saying, @DávidPásztor - but it's just **too risky** in a real world, practical team situation. The fact is, **you simply want this .. "[^0-9]"** so the best thing is to type that. There are any number of cases where Apple have totally screwed-up ISO implementations, you know. And the standard could change - whatever. – Fattie Feb 03 '18 at 23:07
2

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"
vadian
  • 274,689
  • 30
  • 353
  • 361
2

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
Fattie
  • 27,874
  • 70
  • 431
  • 719
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • You should consider using something like this and not hardcode values. If your string looks different then your code will not work. – Rashwan L Sep 10 '17 at 11:13
  • @PenRueda, np. You changed the accepted answer, why if I may ask. – Rashwan L Sep 19 '17 at 11:18
  • I actually tried it, but didnt work. so for now I used the other solution – pgrueda Sep 27 '17 at 03:25
  • 1
    @PenRueda, what didn't work? Create a new class and call it `Extensions` add the extension in there and after that on all your string that you want to do this on just call `.numbersOnly` on whatever class. – Rashwan L Sep 27 '17 at 05:02
  • 1
    This is the only real solution here. Everything else is silly. – Fattie Feb 03 '18 at 21:48
2

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) }
    }
}
Dominik Bucher
  • 2,120
  • 2
  • 16
  • 25
-1

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

Siyavash
  • 970
  • 9
  • 23