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

前端 未结 10 1209
耶瑟儿~
耶瑟儿~ 2020-12-28 12:44

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         


        
相关标签:
10条回答
  • 2020-12-28 13:10

    Use this:

    let aString: String = "This is my string"
    let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "", options:[], range: nil)
    print(newString)
    

    Output : Thisismystring

    0 讨论(0)
  • 2020-12-28 13:12

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

    0 讨论(0)
  • 2020-12-28 13:12

    Swift 4:

    let string = "Test\n with an st\tri\rng"
    print(string.components(separatedBy: .whitespacesAndNewlines))
    // Result: "Test with an string"
    
    0 讨论(0)
  • 2020-12-28 13:15

    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)
    
    0 讨论(0)
提交回复
热议问题