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\"
To remove whitespace from only the beginning and end of a string in Swift:
string.trimmingCharacters(in: .whitespacesAndNewlines)
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
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
}