Remove whitespace character set from string exclud

2019-02-04 14:02发布

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...

6条回答
The star\"
2楼-- · 2019-02-04 14:42

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."
查看更多
爷、活的狠高调
3楼-- · 2019-02-04 14:43

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.
查看更多
狗以群分
4楼-- · 2019-02-04 14:45

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
查看更多
Lonely孤独者°
5楼-- · 2019-02-04 15:00

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.

查看更多
狗以群分
6楼-- · 2019-02-04 15:00

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."
查看更多
Juvenile、少年°
7楼-- · 2019-02-04 15:06

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"
查看更多
登录 后发表回答