tounaobun tounaobun - 20 days ago 5
Swift Question

Does swift have a trim method on String?

Does swift have a trim method on String? For example:

let result = " abc ".trim()
// result == "abc"

Answer

Here's how you remove all the whitespace from the beginning and end of a String.

(Example tested with Swift 2.0.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.stringByTrimmingCharactersInSet(
    NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"

(Example tested with Swift 3.0.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"

Hope this helps.