Swift remove ONLY trailing spaces from string

2.2k views Asked by At

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?

4

There are 4 answers

0
vadian On BEST ANSWER

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)
0
AudioBubble On

Simple. No regular expressions needed.

extension String {

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

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"

0
dijipiji On

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
}