-1

How can I check if a string contains more than one whitespace or period?

I´m using myString.replacingOccurrences(of: ",", with: ".") to change comma to period, is there a similar function to remove whitespaces, or any other character of choice if they occur more than once?

Eccles
  • 394
  • 1
  • 3
  • 13
  • Possible duplicate of [How to remove whitespace in String using pure Swift?](https://stackoverflow.com/questions/32269373/how-to-remove-whitespace-in-string-using-pure-swift) – jscs Aug 10 '19 at 18:30

2 Answers2

0

You can replace whitespace with 'a' using the following code:-

myString.replacingOccurrences(of: " " , with: "a")

Vikas Gupta
  • 188
  • 1
  • 7
0

Use Regular Expression, this removes all occurrences of two or more consecutive whitespaces or periods

myString.replacingOccurrences(of: "[\\s.]{2,}", with: "", options: .regularExpression)

or if you want to keep one whitespace or period respectively you need two filter expressions

myString.replacingOccurrences(of: "\\s{2,}", with: " ", options: .regularExpression)
    .replacingOccurrences(of: "\\.{2,}", with: ".", options: .regularExpression)
vadian
  • 274,689
  • 30
  • 353
  • 361