Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I remove all the empty lines from a string

Tags:

string

ios

swift

I get a string value from an api, and there's a lot of useless empty lines:

bla bla bla


bla

bla bla bla

I want to remove those empty lines to get this result:

bla bla bla
bla
bla bla bla

How can I proceed ?

like image 955
Thomas Avatar asked Mar 09 '16 16:03

Thomas


1 Answers

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"
like image 90
Leo Dabus Avatar answered Oct 12 '22 13:10

Leo Dabus