How to remove multiple spaces in Strings with Swift 2

后端 未结 6 1003
予麋鹿
予麋鹿 2021-02-07 01:23

Until Swift 2 I used this extension to remove multiple whitespaces:

func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByC         


        
6条回答
  •  北海茫月
    2021-02-07 02:06

    Split string to array and then join again in not memory efficient. Its Takes lot of memory. The best way in this case is to scan the given string and perform operations on that. Regular Expression is the advance way to scan a text. For the above conclusion the the solution is given below:

    Swift 4.x

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

    Usages

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

    Output:

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

    You can Do more according to your own requirements but thing I am pointing out here is to use regular expressions with string rather then create arrays which will consume lot of memory.

提交回复
热议问题