如何使用 Swift 删除字符串中的多个空格 2

How to remove multiple spaces in Strings with Swift 2

直到 Swift 2 我使用这个扩展来删除多个空格:

func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty([=11=])})
        return " ".join(components)
}

但是 Swift 2 现在我得到了错误

Cannot invoke 'isEmpty' with an argument list of type '(String)'

现在如何使用 Swift 2 删除多个空格? 谢谢!

Swift2中,join变成了joinWithSeparator,你在数组上调用。

filter 中,应在当前迭代项 [=19=] 上调用 isEmpty

要用您问题中的唯一 space 字符替换白色 space 和换行符:

extension String {
    func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        return components.filter { ![=10=].isEmpty }.joinWithSeparator(" ")
    }
}

let result = "Hello  World.\nHello!".condenseWhitespace()  // "Hello World. Hello!"

因为您的函数不接受任何参数,所以您可以将其设为 属性:

extension String {
    var condensedWhitespace: String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        return components.filter { ![=11=].isEmpty }.joinWithSeparator(" ")
    }
}

let result = "Hello  World.\nHello!".condensedWhitespace  // "Hello World. Hello!"

Swift 3 中有更多变化。

函数:

extension String {
    func condenseWhitespace() -> String {
        let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
        return components.filter { ![=12=].isEmpty }.joined(separator: " ")
    }
}

let result = "Hello  World.\nHello!".condenseWhitespace()

属性:

extension String {
    var condensedWhitespace: String {
        let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
        return components.filter { ![=13=].isEmpty }.joined(separator: " ")
    }
}

let result = "Hello  World.\nHello!".condensedWhitespace

Swift 4.2中NSCharacterSet现在是CharacterSet,你可以省略并使用点语法:

extension String {
    func condenseWhitespace() -> String {
        let components = self.components(separatedBy: .whitespacesAndNewlines)
        return components.filter { ![=14=].isEmpty }.joined(separator: " ")
    }
}

let result = "Hello  World.\nHello!".condenseWhitespace()  // "Hello World. Hello!"

SWIFT 3: 清洁版

extension String {
    var condensedWhitespace: String {
        let components = self.components(separatedBy: .whitespacesAndNewlines)
        return components.filter { ![=10=].isEmpty }.joined(separator: " ")
    }
}

拆分 字符串到数组,然后在内存效率不高 中再次加入。它需要很多内存。在这种情况下,最好的方法是扫描给定的字符串并对其执行操作。 正则表达式是扫描文本的高级方法。针对以上结论,解决方案如下:

Swift 4.x

extension String {

    func removeExtraSpaces() -> String {
        return self.replacingOccurrences(of: "[\s\n]+", with: " ", options: .regularExpression, range: nil)
    }

}

用法

let startingString = "hello   world! \n\n I am   here!"
let processedString = startingString.removeExtraSpaces()
print(processedString)

输出:

processedString => "hello world! I am here!"

你可以根据自己的要求做更多的事情,但我在这里指出的是对字符串使用正则表达式而不是创建会消耗大量内存的数组。

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: " ")

}

这是我的:它是如何工作的。

extension String {

    func removeExtraSpaces() -> String {
        var data  = ""
        var numberOfSpace = 0
        let items = self.getComponents(separatedBy: " ")
        for item in items{
            if item == " "{
                numberOfSpace = numberOfSpace + 1
            }else{
                numberOfSpace = 0
            }
            if numberOfSpace == 1 || numberOfSpace == 0 {
                data =  data + item
                //data.append(item)
            }
        }
        return data
    }
} 

用法

 var message = "What  is the    purpose   of life?"
 message = message.removeExtraSpaces()
 print(message)

输出:

What is the purpose of life?

最干净的版本。有据可查,节省内存,非常易于使用。

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

}

用法:

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

输出:

一个:"Hello I am a string"

b: "HelloIamastring"