How should I remove all the empty lines from a string

edit/update:

Swift 5.2 or later

You can use StringProtocol split method

func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Substring]

And pass a Character property isNewline as KeyPath. Then you just need to use joined(separator: "\n")` to concatenate your string again:

let string = "bla bla bla\n\n\nbla\nbla bla bla\n"
let lines = string.split(whereSeparator: \.isNewline)
let result = lines.joined(separator: "\n")

print(result)  // "bla bla bla\nbla\nbla bla bla"

Or as an extension of StringProtocol:

extension StringProtocol {
    var lines: [SubSequence] { split(whereSeparator: \.isNewline) }
    var removingAllExtraNewLines: String { lines.joined(separator: "\n") }
}

string.lines  // ["bla bla bla", "bla", "bla bla bla"]
string.removingAllExtraNewLines  // "bla bla bla\nbla\nbla bla bla"

Here's an easy way to do it:

import Foundation

let string = "bla bla bla\n\n\nbla\n\nbla bla bla\n"
var filtered = ""
string.enumerateLines({if !$0.line.isEmpty { filtered.appendContentsOf("\($0.line)\n") }})
print(filtered)
// => bla bla bla
// => bla
// => bla bla bla

Another way without creating a mutable variable:

let newString = string.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).filter({!$0.isEmpty}).joinWithSeparator("\n")

MuhammadRaheelMateen's and AtheistP3ace's suggestions are headed in the right direction, but whitespaceCharacterSet‌ would also remove spaces in between words. You should only remove newlineCharacterSet.

But even then, "trimming" would only remove the whitespace at the ends; and as Suthan said, you only want to remove duplicate new lines.

Try separating the string into components separated by newlines, filtering out "", then rejoining with a newline:

let string = blaString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).filter(){$0 != ""}.joinWithSeparator("\n")

Tags:

String

Ios

Swift