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?

1
  • How about rangeOfCharacter(from: .whitespaceAndNewlines.inverted)? Commented Dec 31, 2016 at 22:42

4 Answers 4

11

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)
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

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
}

Comments

0

Simple. No regular expressions needed.

extension String {

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.