Thomas
Thomas

Reputation: 1319

How should I remove all the empty lines from a string

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 ?

Upvotes: 8

Views: 5337

Answers (4)

Leo Dabus
Leo Dabus

Reputation: 236340

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"

Upvotes: 19

Mussa Charles
Mussa Charles

Reputation: 4412

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")

Upvotes: 4

user887210
user887210

Reputation:

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")

Upvotes: 4

Lyndsey Scott
Lyndsey Scott

Reputation: 37290

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")

Upvotes: 2

Related Questions