Remove special characters from a string in Swift
In this tutorial, I will show you how to remove special characters from a string in Swift.
I will go with the basic and easy method first. (It will be useful or not depending on the project that you are working on).
Remove special characters from a string using array of special characters
Steps involved:
- Will create an array containing all the special characters. (You can easily extend or reduce the characters from it as per your requirement)
- Then we will give our string to check.
- We will fetch char by char in a for loop. If a character is not from the special character array then we will append that character to our new string
finalString.
I have created this piece of code:
import Foundation
var specialChar = ["+", "-", "&", "|", "!", "(", ")", "{", "}", "[", "]", "^",
"~", "*", "?", ":","\\", "@","`","#","$","%","_","/",",",".",":","\""]
var string = "HeyTher\"e`@ihh"
var finalString = ""
for char in string {
if !specialChar.contains(String(char)) {
finalString.append(char)
}
}
string = finalString
print(string)Note that: I personally don’t like this method as this will not give you accurate results in all cases.
It’s better to use the opposite to it.
I could create an array that contains a to z, A to Z and 0-9. If any character is found other than this, we can easily remove that. This method will be the most effective.
We can use Regular Expression to achieve the above-mentioned best method:
import Foundation
func codespeedy(from string: String) -> String {
let myPattern = try! NSRegularExpression(pattern: "[^a-zA-Z0-9 ]", options: .caseInsensitive)
let range = NSRange(location: 0, length: string.count)
let finalString = myPattern.stringByReplacingMatches(in: string, options: [], range: range, withTemplate: "")
return finalString
}
let myString = "Wel$%come to Co~^`deSp))eedy%"
let result = codespeedy(from: myString)
print(result)Output:
Welcome to CodeSpeedy
[^a-zA-Z0-9 ] This is the part where I have declared what to keep in my string and what not.
I have inserted a space at the end of that pattern otherwise, it will also remove the spaces and the output would be like this:
WelcometoCodeSpeedy
Using punctuationCharacters
import Foundation
var string = "hello, @ Nice to #meet you"
extension String {
var removedSpecialCharacters: String {
return self.components(separatedBy: CharacterSet.punctuationCharacters).joined(separator: "")
}
}
print(string)
print(string.removedSpecialCharacters)Output:
hello, @ Nice to #meet you hello Nice to meet you
This will also not work for some special characters like: ~ and `.
Leave a Reply