7

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?

user1019042
  • 2,276
  • 8
  • 36
  • 75

4 Answers4

10

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)
vadian
  • 232,468
  • 27
  • 273
  • 287
2

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"

Obliquely
  • 6,539
  • 2
  • 29
  • 50
1

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
}
dijipiji
  • 2,719
  • 24
  • 21
0

Simple. No regular expressions needed.

extension String {

    func trimRight() -> String {
        let c = reversed().drop(while: { $0.isWhitespace }).reversed()
        return String(c)
    }
}
Erik Aigner
  • 28,109
  • 21
  • 129
  • 187