Does swift have a trim method on String? For example:
let result = " abc ".trim() // result == "abc"
The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz".
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered.
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+.)
let myString = " \t\t Let's trim all the whitespace \n \t \n " let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines) // Returns "Let's trim all the whitespace"
Put this code on a file on your project, something likes Utils.swift:
extension String { func trim() -> String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } }
So you will be able to do this:
let result = " abc ".trim() // result == "abc"
Swift 3.0 Solution
extension String { func trim() -> String { return self.trimmingCharacters(in: NSCharacterSet.whitespaces) } }
So you will be able to do this:
let result = " Hello World ".trim() // result = "HelloWorld"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With