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 ?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With