Categories
ios string swift

How to remove all the spaces and \n\r in a String?

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 string.characters {
}

But it’s a little inconvenient.

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 😉