To remove special characters from a string in Swift, you can use the `replacingOccurrences` method with a regular expression pattern.
In this example,
str1
with a value of "Hello! World!"
.replacingOccurrences
method with a regular expression pattern "[^a-zA-Z0-9 ]"
to replace all non-alphanumeric characters and spaces with an empty string.str1
.import Foundation
var str1 = "Hello! World!"
str1 = str1.replacingOccurrences(of: "[^a-zA-Z0-9 ]", with: "", options: .regularExpression)
print("Modified string:", str1)
Modified string: Hello World
In this example,
str2
with a value of "apple@banana"
.replacingOccurrences
method with a regular expression pattern "[^a-zA-Z0-9 ]"
to replace all non-alphanumeric characters and spaces with an empty string.str2
.import Foundation
var str2 = "apple@banana"
str2 = str2.replacingOccurrences(of: "[^a-zA-Z0-9 ]", with: "", options: .regularExpression)
print("Modified string:", str2)
Modified string: applebanana
In this tutorial, we learned How to Remove Special Characters from a String in Swift language with well detailed examples.