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

mpgws1up  于 2022-11-06  发布在  Swift
关注(0)|答案(6)|浏览(202)

在Swift 2之前,我使用这个扩展来删除多个空格:

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

但现在使用Swift 2时,我得到了错误
无法使用类型为“(String)”的参数列表调用“isEmpty”
我现在怎么能用雨燕2删除多个空格呢?Thnx!

bxgwgixi

bxgwgixi1#

Swift 2中,join已经变成了joinWithSeparator,您可以在数组上调用它。
filter中,isEmpty应该在目前的反覆项目$0上呼叫。
如您的问题所示,将空格和换行符替换为唯一的空格字符:

extension String {
    func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        return components.filter { !$0.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 { !$0.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 { !$0.isEmpty }.joined(separator: " ")
    }
}

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

属性:

extension String {
    var condensedWhitespace: String {
        let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
        return components.filter { !$0.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 { !$0.isEmpty }.joined(separator: " ")
    }
}

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

nqwrtyyt2#

Splitstring to array,然后joininnot memory efficient.它占用大量内存.在这种情况下,最好的方法是扫描给定的字符串并对其执行操作.正则表达式是扫描文本的高级方法.对于上述结论,下面给出了解决方案:
斯威夫特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 =〉“你好,世界!我在这里!"
你可以根据自己的要求做更多的事情,但我在这里指出的是,使用正则表达式与字符串,而不是创建数组,这将消耗大量的内存。

0mkxixxg

0mkxixxg3#

最干净的版本。有文档记录,内存效率高,非常易于使用。

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

输出:

a:“你好我是一根弦”
B:“你好大串”

hec6srdp

hec6srdp4#

SWIFT 3:更干净的版本

extension String {
    var condensedWhitespace: String {
        let components = self.components(separatedBy: .whitespacesAndNewlines)
        return components.filter { !$0.isEmpty }.joined(separator: " ")
    }
}
3j86kqsm

3j86kqsm5#

我的答案是:它是如何运作的。

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)

输出:

人生的目的是什么?

cu6pst1q

cu6pst1q6#

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

}

相关问题