How to replace multiple spaces in a string with a single space between words in Swift

1 Answer

0 votes
import Foundation

func replaceMultipleSpaces(_ str: String) -> String {
    // Use a regular expression to replace multiple spaces with a single space
    let regex = try! NSRegularExpression(pattern: "\\s+", options: [])
    let range = NSRange(location: 0, length: str.utf16.count)
    let result = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: " ")

    // Optionally trim leading and trailing spaces
    return result.trimmingCharacters(in: .whitespacesAndNewlines)
}

let str = "   This   is    a   string   with   multiple    spaces   "
let outputString = replaceMultipleSpaces(str)

print("\"\(outputString)\"")



/*
run:

"This is a string with multiple spaces"

*/

 



answered Apr 5 by avibootz
...