user1019042
user1019042

Reputation: 2218

Swift remove ONLY trailing spaces from string

many examples in SO are fixing both sides, the leading and trailing. My request is only about the trailing. My input text is: " keep my left side " Desired output: " keep my left side"

Of course this command will remove both ends:

let cleansed = messageText.trimmingCharacters(in: .whitespacesAndNewlines)

Which won't work for me.

How can I do it?

Upvotes: 7

Views: 2371

Answers (4)

user187676
user187676

Reputation:

Simple. No regular expressions needed.

extension String {

    func trimRight() -> String {
        let c = reversed().drop(while: { $0.isWhitespace }).reversed()
        return String(c)
    }
}

Upvotes: 0

dijipiji
dijipiji

Reputation: 3109

Building on vadian's answer I found for Swift 3 at the time of writing that I had to include a range parameter. So:

func trailingTrim(with string : String) -> String {

    let start = string.startIndex
    let end = string.endIndex
    let range: Range<String.Index> = Range<String.Index>(start: start, end: end)


    let cleansed:String = string.stringByReplacingOccurrencesOfString("\\s+$",
                                                                      withString: "",
                                                                      options: .RegularExpressionSearch,
                                                                      range: range)

    return cleansed
}

Upvotes: 1

Obliquely
Obliquely

Reputation: 7072

You can use the rangeOfCharacter function on string with a characterSet. This extension then uses recursion of there are multiple spaces to trim. This will be efficient if you only usually have a small number of spaces.

extension String {
    func trailingTrim(_ characterSet : CharacterSet) -> String {
        if let range = rangeOfCharacter(from: characterSet, options: [.anchored, .backwards]) {
            return self.substring(to: range.lowerBound).trailingTrim(characterSet)
        }
        return self
    }
}

"1234 ".trailingTrim(.whitespaces)

returns

"1234"

Upvotes: 2

vadian
vadian

Reputation: 285072

A quite simple solution is regular expression, the pattern is one or more(+) whitespace characters(\s) at the end of the string($)

let string = " keep my left side "
let cleansed = string.replacingOccurrences(of: "\\s+$", 
                                         with: "", 
                                      options: .regularExpression)

Upvotes: 10

Related Questions