To replace multiple spaces with a single space in Swift, you can use regular expressions with the replacingOccurrences
method of the String class.
In this example,
str
with a string value containing multiple spaces.\s+
to match one or more whitespace characters.replacingOccurrences
method of the string object str
to replace all occurrences of the pattern with a single space.import Foundation
let str = "Hello World from Swift"
let modifiedStr = str.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
print("Modified string: \(modifiedStr)")
Modified string: Hello World from Swift
In this example,
str1
with a string value containing multiple spaces.\s+
to match one or more whitespace characters.replacingOccurrences
method of the string object str1
to replace all occurrences of the pattern with a single space.import Foundation
let str1 = "Swift is a powerful language"
let modifiedStr1 = str1.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
print("Modified string: \(modifiedStr1)")
Modified string: Swift is a powerful language
In this tutorial, we learned How to Replace multiple Spaces with a Single Space in String in Swift language with well detailed examples.