-2

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?

1

2 Answers 2

1

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)

In Swift 5.7+ the syntax has become much cleaner

myString.replacing(/[\s.]{2,}/, with: "")
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

1 Comment

I want to allow one white space, and/or one period. This will remove all whitespaces

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.