1

I'm looking for a way to remove dollar signs, commas and periods using a single line of code (I'm able to do it using replacingOccurrences 3x). I found trimmingCharacters(:_) but for some reason it doesn't remove commas and periods (at least not all the time).

This is what I get in Xcode 8.1 playground:

var myString = "$3,000.50"

myString.trimmingCharacters(in: CharacterSet(charactersIn: "$.,")) //"3,000.50"

myString.trimmingCharacters(in: CharacterSet(charactersIn: myString)) //""

Can someone help me understand why this doesn't work? Thanks.

Ruben Steins
  • 2,782
  • 4
  • 27
  • 48
Jack Ngai
  • 157
  • 1
  • 9
  • 1
    `remove dollar signs, commas and periods` So, the expected result should be "300050", right? – Eric Aya Dec 09 '16 at 15:29
  • 1
    Take a look at the documentation for [`trimmingCharacters(in:)`](https://developer.apple.com/reference/swift/string/1643030-trimmingcharacters) – it only removes characters from the *ends* of the string. – Hamish Dec 09 '16 at 15:33
  • @EricAya Yes. That's the expected result. – Jack Ngai Dec 09 '16 at 16:58
  • @Hamish The documentations saids both ends of the string, so it should work. I just tested by changing myString to "hello" and change the CharacterSet to "he" and confirmed the remaining string is "llo". – Jack Ngai Dec 09 '16 at 17:01
  • 1
    @jackngai Your first example works for "$" because it's at the start of the string, and doesn't work for "," and "." which are *not* at the start or end of the string - as expected. :) – Eric Aya Dec 09 '16 at 17:09
  • http://stackoverflow.com/a/29783546/2303865 – Leo Dabus Dec 09 '16 at 21:17
  • @EricAya I switched the CharacterSet to ",$." (so the $ is not on either end) and the $ is still the only character that was removed. – Jack Ngai Dec 10 '16 at 16:38
  • 1
    @EricAya I think I'm getting an idea of how this method works. If I change myString is "$$$$.,500,00,,,,", it will remove each character from both ends that is part of the CharacterSet, and then stops when it finds one that doesn't match, leaving me with "500,00". So this method won't do what I need. But thanks for helping me understand it. – Jack Ngai Dec 10 '16 at 17:51
  • 1
    @LeoDabus I essentially distilled the code from your post to this: `extension String { var numbers: String { return components(separatedBy: Numbers.characterSet.inverted).joined() } var integer: Int { return Int(numbers) ?? 0 } } struct Numbers { static let characterSet = CharacterSet(charactersIn: "0123456789") } extension NumberFormatter { convenience init(numberStyle: NumberFormatter.Style) { self.init() self.numberStyle = numberStyle } }` While it is not a single line, it does do what I need. So thanks for this. – Jack Ngai Dec 10 '16 at 18:01

0 Answers0