To remove all whitespace characters from a string in Swift, you can use the `replacingOccurrences` method with the `\s` regular expression pattern.
In this example,
str
with a value of "Hello World"
.replacingOccurrences
method with the regular expression pattern "\\s"
to replace all whitespace characters (including tabs, spaces, newlines, etc.) with an empty string in str
.str
to the console.import Foundation
let str = "Hello World"
let modifiedStr = str.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)
print("Modified string:", modifiedStr)
Modified string: HelloWorld
In this example,
str
with a value of "apple\tbanana\n cherry "
.replacingOccurrences
method with the regular expression pattern "\\s"
to replace all whitespace characters (including tabs, spaces, newlines, etc.) with an empty string in str
.str
to the console.import Foundation
let str = "apple\tbanana\n cherry "
let modifiedStr = str.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)
print("Modified string:", modifiedStr)
Modified string: applebananacherry
In this tutorial, we learned How to Remove All Whitespace Characters from a String in Swift language with well detailed examples.