What is the most efficient way to remove all the spaces, \\n
and \\r
in a String in Swift?
I have tried:
for character in s
Use this:
let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "", options:[], range: nil)
print(newString)
Output : Thisismystring
Swift 4:
let text = "This \n is a st\tri\rng"
let test = String(text.filter { !" \n\t\r".contains($0) })
Output:
print(test) // Thisisastring
While Fahri's answer is nice, I prefer it to be pure Swift ;)
Swift 4:
let string = "Test\n with an st\tri\rng"
print(string.components(separatedBy: .whitespacesAndNewlines))
// Result: "Test with an string"
If by spaces you mean whitespaces, be aware that more than one whitespace character exists, although they all look the same.
The following solution takes that into account:
Swift 5:
extension String {
func removingAllWhitespaces() -> String {
return removingCharacters(from: .whitespaces)
}
func removingCharacters(from set: CharacterSet) -> String {
var newString = self
newString.removeAll { char -> Bool in
guard let scalar = char.unicodeScalars.first else { return false }
return set.contains(scalar)
}
return newString
}
}
let noNewlines = "Hello\nWorld".removingCharacters(from: .newlines)
print(noNewlines)
let noWhitespaces = "Hello World".removingCharacters(from: .whitespaces)
print(noWhitespaces)