本文介绍了从字符串中删除空白字符集,不包括空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

How can I remove the whitespace character set from a string but keep the single spaces between words. I would like to remove double spaces and triple spaces, etc...

推荐答案

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.

旧版 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 扩展名:

or if you'd like it as a String extension:

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.

全部归功于 NSCharacterSet 上的 NSHipster 帖子.

这篇关于从字符串中删除空白字符集,不包括空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 20:53