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

For the sake of completeness this is the Regular Expression version

let string = "What is the most efficient way to remove all the spaces and \n \r \tin a String in Swift"
let stringWithoutWhitespace = string.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)
// -> "WhatisthemostefficientwaytoremoveallthespacesandinaStringinSwift"

edit/update:

Swift 5.2 or later

We can use the new Character property isWhitespace


let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.filter { !$0.isWhitespace }

result  //  "Line1Line2"

extension StringProtocol where Self: RangeReplaceableCollection {
    var removingAllWhitespaces: Self {
        filter(\.isWhitespace.negated)
    }
    mutating func removeAllWhitespaces() {
        removeAll(where: \.isWhitespace)
    }
}

extension Bool {
    var negated: Bool { !self }
}

let textInput = "Line 1 \n Line 2 \n\r"
let result = textInput.removingAllWhitespaces   //"Line1Line2"

var test = "Line 1 \n Line 2 \n\r"
test.removeAllWhitespaces()
print(test)  // "Line1Line2"

Note: For older Swift versions syntax check edit history


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 ;)

Tags:

String

Ios

Swift