How to remove multiple spaces in Strings with Swift 2

后端 未结 6 1020
予麋鹿
予麋鹿 2021-02-07 01:23

Until Swift 2 I used this extension to remove multiple whitespaces:

func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByC         


        
6条回答
  •  执念已碎
    2021-02-07 01:53

    Cleanest version. Documented, memory efficient, extremely easy to use.

    extension String {
    
        /// Returns a condensed string, with no extra whitespaces and no new lines.
        var condensed: String {
            return replacingOccurrences(of: "[\\s\n]+", with: " ", options: .regularExpression, range: nil)
        }
    
        /// Returns a condensed string, with no whitespaces at all and no new lines.
        var extraCondensed: String {
            return replacingOccurrences(of: "[\\s\n]+", with: "", options: .regularExpression, range: nil)
        }
    
    }
    

    Usage:

    let a = " Hello\n  I am  a string  ".condensed
    let b = " Hello\n  I am  a string  ".extraCondensed
    

    Output:

    a: "Hello I am a string"

    b: "HelloIamastring"

提交回复
热议问题