How to trim whitespaces and other characters from a string in swift

Swift program to trim whitespace in a string:

This program will show you how to trim whitespace from a string. We can use trimmingCharacters method to trim whitespaces from a string in Swift. This method is defined as below:

trimmingCharacters(in set: CharacterSet) -> String

It returns one new string made by removing from both sides as defined by the CharacterSet. The parameter set must not be nil. It is the character set that is used to remove characters from the given string.

Example of trimmingCharacters:

Let’s check different examples of trimmingCharacters :

1. Trimming decimal digits:

The below program will trim decimal digits from both end of the string:

import Foundation

let given_str = "5589  hello world  123"
let new_str = given_str.trimmingCharacters(in: .decimalDigits)
print(new_str)

It will give the below output:

  hello world  

2. Trimming whitespace:

We can use whitespace as CharacterSet to trim whitespace from both end of the string:

import Foundation

let given_str = "  hello world  "
let new_str = given_str.trimmingCharacters(in: .whitespaces)
print(new_str)

It will print:

hello world

3. Trimming whitespace and newlines:

whitespacesAndNewlines is used to trim whitespace and newlines:

import Foundation

let given_str = "\n  hello world  \n"

let new_str = given_str.trimmingCharacters(in: .whitespacesAndNewlines)
print(new_str)

This program will remove the new lines \n and whitespaces from the given_str.

hello world

trim whitespace in string ios swift

You might also like: