Trimming String in Swift

Using UIKit

UIKit has defined string trimming API: trimmingCharacters, is little* verbose. It accepts a CharacterSet, explaining which characters to cut off the boundary of a string. Character Set also defines predefined constants to explain frequently used character sets.

  • .whitespaces explains whitespaces character ( space and tab)
  • .whitespacesAndNewlines explaines all whitespaces characters
  • decimalDigits explaines numbers

To trim off whitespaces:

import UIKIT
let name = "  Superman  "
let trimmedName = name. trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)


Output of the above code


Using Foundation

Foundation also defined the same API for trimming strings, but this can be used using NSCharacterSet class for explaining the characters.

import Foundation
let name = "  Superman  "
let trimmedName = name.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)


The output of above code


Be Updated

Only articles are shared on Medium

This site uses cookies to gather website usage and performance data.