-1

I want to store float to CoreData and I want to convert every of the following inputs to 90.5:

  • 90.5
  • 90,5
  • 90.5
  • 90, 5

That means: Remove whitespace and convert , to .

Is this code best practice?

let str = "  90, 5  "
let converted = str.trimmingCharacters(in: .whitespacesAndNewlines)
let converted = strWithoutWithespace.replacingOccurrences(of: ",", with: ".")
pawello2222
  • 46,897
  • 22
  • 145
  • 209
T. Karter
  • 638
  • 7
  • 25
  • Does this answer your question? [How should I remove all the leading spaces from a string? - swift](https://stackoverflow.com/questions/28570973/how-should-i-remove-all-the-leading-spaces-from-a-string-swift) – Joakim Danielson Jul 02 '20 at 08:31

1 Answers1

0

No, it's not because it doesn't remove the space within the string.

The regex pattern "\\s+" removes all occurrences of one or more whitespace characters.

let str = "  90, 5  "
let strWithoutWhitespace = str.replacingOccurrences(of: "\\s+", with: "", options: .regularExpression)
let converted = strWithoutWhitespace.replacingOccurrences(of: ",", with: ".")
vadian
  • 274,689
  • 30
  • 353
  • 361