Swift 3
extension String { func condenseWhitespace() -> String { return self.components(separatedBy: CharacterSet.whitespacesAndNewlines) .filter { !$0.isEmpty } .joined(separator: " ") } } let string = " Lorem \r ipsum dolar sit amet. " print(string.condensingWhitespace()) // Lorem ipsum dolar sit amet.
遗产快报
NSCharacterSet使这很容易:
func condenseWhitespace(string: String) -> String { let components = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!isEmpty($0)}) return join(" ",components) } var string = " Lorem \r ipsum dolar sit amet. " println(condenseWhitespace(string)) // Lorem ipsum dolar sit amet.
或者如果您希望将其作为字符串扩展名:
extension String { func condenseWhitespace() -> String { let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)}) return " ".join(components) } } var string = " Lorem \r ipsum dolar sit amet. " println(string.condenseWhitespace()) // Lorem ipsum dolar sit amet.