#03: String trimming in Swift 3

In another short post we’ve seen how to split strings in Swift, this post will show you how to trim them form surrounding spaces or other unwanted characters.

This can be done quite easily leveraging the NSString class from Foundation.

In the snippet below, we’ll remove the whitespaces an the trailing newline that surround a Shakespeare quote:


import Foundation

var aline = "  This above all: to thine own self be true        \n"
aline.trimmingCharacters(in: .whitespacesAndNewlines) //This above all: to thine own self be true

There are a few default CharacterSet provided via static property to choose from in addition to the whitespacesAndNewlines we used here.

Value Description
.controlCharacters Characters in Unicode General Category Cc and Cf.
.whitespaces Characters in Unicode General Category Zs and CHARACTER TABULATION (U+0009).
.whitespacesAndNewlines Characters in Unicode General Category Z*, U+000A ~ U+000D, and U+0085.
.decimalDigits Characters in the category of Decimal Numbers.
.letters Characters in Unicode General Category L* & M*.
.lowercaseLetters Characters in Unicode General Category Ll.
.uppercaseLetters Characters in Unicode General Category Lu and Lt.
.nonBaseCharacters Characters in Unicode General Category M*.
.alphanumerics Characters in Unicode General Categories L, M, and N*.
.decomposables Individual Unicode characters that can also be represented as composed character sequences (such as for letters linked with accents)
.illegalCharacters Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
.punctuationCharacters Characters in Unicode General Category P*.
.capitalizedLetters Characters in Unicode General Category Lt.
.symbols Characters in Unicode General Category S*.
.newlines Containing the newline characters (U+000A ~ U+000D, U+0085, U+2028, and U+2029).
.urlUserAllowed Characters allowed in a user URL subcomponent.
.urlPasswordAllowed Characters allowed in a password URL subcomponent.
.urlHostAllowed Characters allowed in a host URL subcomponent.
.urlPathAllowed Characters allowed in a path URL component.
.urlQueryAllowed Characters allowed in a query URL component.
.urlFragmentAllowed Characters allowed in a fragment URL component.

Additionally, custom set of characters can be created specifying all the characters you need in a string:


var myCharset= CharacterSet("#%&")
aline.trimmingCharacters(in: myCharset)

Did you like this article? Let me know on Twitter or subscribe for updates!


I'm also on Twitter and GitHub.

Subscribe via RSS or email.