Sling Academy
Home/Swift/Swift: Remove Leading and Trailing Whitespace of a String

Swift: Remove Leading and Trailing Whitespace of a String

Last updated: February 23, 2023

This practical article walks you through a couple of different examples that demonstrate how to remove leading and trailing whitespace, separately or together, from a string in Swift.

Trim both leading and trailing whitespace

You can use the built-in trimmingCharacters(in:) method with the CharacterSet.whitespaces argument to remove both leading and trailing whitespace from a string.

Example:

import Foundation

let str = "  slingacademy.com   "
let trimmedStr = str.trimmingCharacters(in: .whitespaces)

print(trimmedStr) 
print("The length of the original string is \(str.count)")
print("The length of the trimmed string is \(trimmedStr.count)")

Output:

slingacademy.com
The length of the original string is 21
The length of the trimmed string is 16

A common real-world use case for trimming both leading and trailing whitespace is cleaning up user input from a text field or removing extraneous whitespace from a file name.

Only remove the leading whitespace

There might be cases where you only want to trim the leading white space of a given string. The example below will show you how to do that.

Example:

import Foundation

let str = "   Trim leading whitespace, preserve trailing whitespace.  "

let leadingWhitespace = str.prefix(while: {$0.isWhitespace})
let trimmedStr = String(str[leadingWhitespace.endIndex...])
print("Output: '\(trimmedStr)'") 

Output:

Output: 'Trim leading whitespace, preserve trailing whitespace.  '

You can also use regular expressions to handle this task:

import Foundation

let str = "   Trim leading whitespace, preserve trailing whitespace.  "
let pattern = "^\\s+"
let regex = try! NSRegularExpression(pattern: pattern)
let range = NSRange(str.startIndex..., in: str)
let trimmed = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: "")

print("Output: '\(trimmed)'")

Output:

Output: 'Trim leading whitespace, preserve trailing whitespace.  '

Only remove trailing whitespace

Real-world use cases for this might include formatting text for display, such as preserving the indentation of code blocks or working with text files that have whitespace at the beginning of each line.

You can use the replacingOccurrences() method with a regular expression pattern to remove the trailing whitespace (and still keep the leading whitespace) from a string.

Example:

import Foundation

let str = "   Remove trailing whitespace but keep leading whitespace     "
let pattern = "\\s+$"
let regex = try! NSRegularExpression(pattern: pattern)
let range = NSRange(str.startIndex..., in: str)
let trimmed = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: "")

print("Trimmed: \(trimmed)")
print("Lenght of original string: \(str.count)")
print("Lenght of trimmed string: \(trimmed.count)")

Output:

Trimmed:    Remove trailing whitespace but keep leading whitespace
Lenght of original string: 62
Lenght of trimmed string: 57

Next Article: Swift: 3 ways to count the occurrences of words in a string

Previous Article: 2 Ways to Reverse a String in Swift

Series: Working with Strings in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)