从不包含空格的字符串中删除空白字符集

时间:2014-11-16 23:33:42

标签: string swift whitespace

如何从字符串中删除空白字符集,但保留字之间的单个空格。我想删除双空格和三重空格等...

6 个答案:

答案 0 :(得分:49)

Swift 3

extension String {
    func condensingWhitespace() -> String {
        return self.components(separatedBy: .whitespacesAndNewlines)
            .filter { !$0.isEmpty }
            .joined(separator: " ")
    }
}

let string = "  Lorem   \r  ipsum dolar   sit  amet. "
print(string.condensingWhitespace())
// Lorem ipsum dolar sit amet.

Legacy Swift

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.

或者如果您希望将其作为String扩展程序:

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.

归功于NSHipster post on NSCharacterSet

答案 1 :(得分:11)

Swift 2兼容代码:

extension String {
    var removeExcessiveSpaces: String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        let filtered = components.filter({!$0.isEmpty})
        return filtered.joinWithSeparator(" ")
    }
}

用法:

let str = "test  spaces    too many"
print(str.removeExcessiveSpaces)
// Output: test spaces too many

答案 2 :(得分:4)

当你有Objective-C / Foundation背景时,将componentsSeparatedByCharactersInSet(:)与Swift一起使用可能显而易见,以便将字符串从其冗余的空白字符中修剪。

这里的步骤是从你的字符串中获取一个String数组,其中所有空格字符都被空字符串替换,以将此数组过滤为String的新数组,其中所有空字符串都有已删除并将此数组的所有字符串连接到一个新字符串,同时用空格字符分隔它们。

以下Playground代码显示了如何执行此操作:

import Foundation

let string = "  Lorem   ipsum dolar   sit  amet. "

let newString = string
.componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
.filter { !$0.isEmpty }
.joinWithSeparator(" ") 

print(newString) // prints "Lorem ipsum dolar sit amet."

如果您需要重复此操作,可以将代码重构为String扩展名:

import Foundation

extension String {
    func condenseWhitespace() -> String {
        return componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
            .filter { !$0.isEmpty }
            .joinWithSeparator(" ")
    }
}

let string = "  Lorem   ipsum dolar   sit  amet. "
let newString = string.condenseWhitespace()

print(newString) // prints "Lorem ipsum dolar sit amet."

但是,使用Swift,还有另一种方法可以实现功能,并且不需要您导入Foundation

这里的步骤是从您的字符串中获取一个String.CharacterView数组,其中删除了所有空格字符,将此String.CharacterView数组映射到String数组并加入将这个数组的所有字符串转换为一个新的字符串,同时用空白字符分隔它们。

以下Playground代码显示了如何执行此操作:

let string = "  Lorem   ipsum dolar   sit  amet. "

let newString = string.characters
    .split { $0 == " " }
    .map { String($0) }
    .joinWithSeparator(" ")

print(newString) // prints "Lorem ipsum dolar sit amet."

如果您需要重复此操作,可以将代码重构为String扩展名:

extension String {
    func condenseWhitespace() -> String {
        return characters
            .split { $0 == " " }
            .map { String($0) }
            .joinWithSeparator(" ")
    }
}

let string = "  Lorem   ipsum dolar   sit  amet. "
let newString = string.condenseWhitespace()

print(newString) // prints "Lorem ipsum dolar sit amet."

答案 3 :(得分:0)

对于swift 3.1

extension String {
    var trim : String {
        get {
            return characters
                .split { $0 == " " || $0 == "\r" }
                .map { String($0) }
                .joined(separator: " ")
        }
    }
}

let string = "  Lorem   \r  ipsum dolar   sit  amet. "
print(string.trim)

将输出:

Lorem ipsum dolar sit amet.

答案 4 :(得分:0)

另一种选择是使用正则表达式搜索来替换所有 单个空格出现一个或多个空白字符。 示例(Swift 3):

let string = "  Lorem   \r  ipsum dolar   sit  amet. "

let condensed = string
        .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
        .trimmingCharacters(in: .whitespacesAndNewlines)

print(condensed.debugDescription) // "Lorem ipsum dolar sit amet."

答案 5 :(得分:-1)

您可以在我写的https://bit.ly/JString

的Swift String扩展中使用trim()方法
var string = "hello  "
var trimmed = string.trim()
println(trimmed)// "hello"