Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does swift have a trim method on String?

Tags:

string

trim

swift

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

let result = " abc ".trim() // result == "abc" 
like image 779
tounaobun Avatar asked Nov 07 '14 09:11

tounaobun


People also ask

Is trim a string method?

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".

How do you trim values in a string?

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.

How do I remove spaces from a string in Swift?

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.


2 Answers

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" 
like image 81
Sivanraj M Avatar answered Oct 04 '22 04:10

Sivanraj M


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" 
like image 32
Thiago Arreguy Avatar answered Oct 04 '22 04:10

Thiago Arreguy