Search code examples
swiftswift3trim

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

Solution

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