How to replace duplicate spaces in a string with Swift

1 Answer

0 votes
import Foundation

extension String {
    func replaceDuplicateSpaces() -> String {
        return self.replacingOccurrences(of: "[\\s\n]+", with: " ", options: .regularExpression, range: nil)
    }
}

var s = "  Swift    programming    language for  macOS and  iOS  "

s = s.replaceDuplicateSpaces()
s = s.trimmingCharacters(in: .whitespaces)

print(s)



/*
run:

Swift programming language for macOS and iOS

*/

 



answered Dec 24, 2024 by avibootz
...