How to remove multiple spaces in Strings with Swift 2

后端 未结 6 1008
予麋鹿
予麋鹿 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 02:11

    var str = "Hello  World.\nHello!"
    
    if let regex = try? NSRegularExpression(pattern: "\\s+", options:NSRegularExpression.Options.caseInsensitive)
    {
        str = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.count), withTemplate: " ")
    
    }
    

提交回复
热议问题