Trim spaces from end of a NSString

前端 未结 14 1070
既然无缘
既然无缘 2020-11-27 09:26

I need to remove spaces from the end of a string. How can I do that? Example: if string is \"Hello \" it must become \"Hello\"

相关标签:
14条回答
  • 2020-11-27 10:00

    To remove whitespace from only the beginning and end of a string in Swift:

    Swift 3

    string.trimmingCharacters(in: .whitespacesAndNewlines)
    

    Previous Swift Versions

    string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
    
    0 讨论(0)
  • 2020-11-27 10:03

    This will remove only the trailing characters of your choice.

    func trimRight(theString: String, charSet: NSCharacterSet) -> String {
    
        var newString = theString
    
        while String(newString.characters.last).rangeOfCharacterFromSet(charSet) != nil {
            newString = String(newString.characters.dropLast())
        }
    
        return newString
    }
    
    0 讨论(0)
提交回复
热议问题