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

前端 未结 10 1259
耶瑟儿~
耶瑟儿~ 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:07

    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 { !$0.isWhitespace }
        }
        mutating func removeAllWhitespaces() {
            removeAll(where: \.isWhitespace)
        }
    }
    

    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

提交回复
热议问题