Swift remove ONLY trailing spaces from string

荒凉一梦 提交于 2019-12-10 12:57:15

问题


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:


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)



回答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"




回答3:


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
}


来源:https://stackoverflow.com/questions/41412161/swift-remove-only-trailing-spaces-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!