19

How can I remove the whitespace character set from a string but keep the single spaces between words. I would like to remove double spaces and triple spaces, etc...

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Tom Coomer
  • 6,227
  • 12
  • 45
  • 82

6 Answers6

51

Swift 3

extension String {
    func condensingWhitespace() -> String {
        return self.components(separatedBy: .whitespacesAndNewlines)
            .filter { !$0.isEmpty }
            .joined(separator: " ")
    }
}

let string = "  Lorem   \r  ipsum dolar   sit  amet. "
print(string.condensingWhitespace())
// Lorem ipsum dolar sit amet.

Legacy Swift

NSCharacterSet makes this easy:

func condenseWhitespace(string: String) -> String {
    let components = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!isEmpty($0)})
    return join(" ", components)
}

var string = "  Lorem   \r  ipsum dolar   sit  amet. "
println(condenseWhitespace(string))
// Lorem ipsum dolar sit amet.

or if you'd like it as a String extension:

extension String {
    func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)})
        return " ".join(components)
    }
}

var string = "  Lorem   \r  ipsum dolar   sit  amet. "
println(string.condenseWhitespace())
// Lorem ipsum dolar sit amet.

All credit to the NSHipster post on NSCharacterSet.

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
11

Swift 2 compatible code:

extension String {
    var removeExcessiveSpaces: String {
        let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        let filtered = components.filter({!$0.isEmpty})
        return filtered.joinWithSeparator(" ")
    }
}

Usage:

let str = "test  spaces    too many"
print(str.removeExcessiveSpaces)
// Output: test spaces too many
Vasily
  • 3,740
  • 3
  • 27
  • 61
4

When you have an Objective-C/Foundation background, it may seem obvious to use componentsSeparatedByCharactersInSet(:) with Swift in order to trim your string from its redundant whitespace characters.

The steps here are to get from your string an array of String where all whitespace characters have been replaced by empty strings, to filter this array into a new array of String where all empty strings have been removed and to join all the strings of this array into a new string while separating them by a whitespace character.

The following Playground code shows how to do it this way:

import Foundation

let string = "  Lorem   ipsum dolar   sit  amet. "

let newString = string
.componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
.filter { !$0.isEmpty }
.joinWithSeparator(" ") 

print(newString) // prints "Lorem ipsum dolar sit amet."

If you need to repeat this operation, you can refactor your code into a String extension:

import Foundation

extension String {
    func condenseWhitespace() -> String {
        return componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
            .filter { !$0.isEmpty }
            .joinWithSeparator(" ")
    }
}

let string = "  Lorem   ipsum dolar   sit  amet. "
let newString = string.condenseWhitespace()

print(newString) // prints "Lorem ipsum dolar sit amet."

However, with Swift, there is another way that is really functional and that does not require you to import Foundation.

The steps here are to get from your string an array of String.CharacterView where all whitespace characters have been removed, to map this array of String.CharacterView to an array of String and to join all the strings of this array into a new string while separating them by a whitespace character.

The following Playground code shows how to do it this way:

let string = "  Lorem   ipsum dolar   sit  amet. "

let newString = string.characters
    .split { $0 == " " }
    .map { String($0) }
    .joinWithSeparator(" ")

print(newString) // prints "Lorem ipsum dolar sit amet."

If you need to repeat this operation, you can refactor your code into a String extension:

extension String {
    func condenseWhitespace() -> String {
        return characters
            .split { $0 == " " }
            .map { String($0) }
            .joinWithSeparator(" ")
    }
}

let string = "  Lorem   ipsum dolar   sit  amet. "
let newString = string.condenseWhitespace()

print(newString) // prints "Lorem ipsum dolar sit amet."
Community
  • 1
  • 1
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218
  • 1
    this gets of spaces, but not tabs, or new lines, or anything else that might abstractly be defined as white space (though I'd love to see a non-Foundation solution to determining if a swift Character is a white space character) – bshirley Aug 05 '16 at 18:56
0

For swift 3.1

extension String {
    var trim : String {
        get {
            return characters
                .split { $0 == " " || $0 == "\r" }
                .map { String($0) }
                .joined(separator: " ")
        }
    }
}

let string = "  Lorem   \r  ipsum dolar   sit  amet. "
print(string.trim)

Will output :

Lorem ipsum dolar sit amet.
0

Another option is to use regular expression search to replace all occurrences of one or more whitespace characters by a single space. Example (Swift 3):

let string = "  Lorem   \r  ipsum dolar   sit  amet. "

let condensed = string
        .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
        .trimmingCharacters(in: .whitespacesAndNewlines)

print(condensed.debugDescription) // "Lorem ipsum dolar sit amet."
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
-1

You can use the trim() method in a Swift String extension I wrote https://bit.ly/JString.

var string = "hello  "
var trimmed = string.trim()
println(trimmed)// "hello"
William Falcon
  • 9,813
  • 14
  • 67
  • 110
  • I looked up your source code, but I don't think this does what the OP asked (ie, remove double and triple spaces and replace them with a single space.) If I'm wrong let me know and I'll reverse the downvote. – Suragch Aug 15 '15 at 03:15
  • This removes n spaces and replaces them with no space. Exactly what the python trim method does. To remove spaces > 1, use a regex. – William Falcon Aug 15 '15 at 06:03
  • 1
    But what if you have multiple spaces in middle of a string? For example, `"hello________there"` (using underscore to represent space) – Suragch Aug 15 '15 at 06:13
  • the OP asked only for only removing spaces a the beginning of the string, so this answer is not correct – Macistador Jan 03 '17 at 14:39
  • works also for the front. But it's cool to comment on stuff 1 year later – William Falcon Jan 03 '17 at 15:01