How should I remove all the empty lines from a string

Viewed 4032

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 ?

4 Answers

Swift 5.1 one line version

This removes all extra(at the end of the text) and intermediate spaces.

    let extraSpaceRemoveText = text.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: .newlines).filter{!$0.isEmpty}.joined(separator: "\n")
Related