Home
Swift
String Trim
Updated Aug 20, 2023
Dot Net Perls
Trim. Often strings contain whitespace (like spaces or newlines) at their starts or ends. These characters are often removed or trimmed.
In Foundation, using Swift 5.8, we can access a method called trimmingCharacters. A character set is required. The result is a string with the specified characters removed.
An example. Let us begin with a simple example. We introduce a "source" string that contains a leading space, and a trailing period and space.
Start We create a CharacterSet with 3 characters—a space, period, and a question mark.
Next We invoke the trim method, trimmingCharacters. We pass the set instance as an argument.
Result The string returned has no leading or trailing spaces (and no period).
import Foundation // The string we are trimming. let source = " Programming in Swift. " // Create a character set of chars to trim. let set = CharacterSet(charactersIn: " .?") // Call func with character set. let result = source.trimmingCharacters(in: set) // Write the result. print(result)
Programming in Swift
An alternative. A custom pair of loops (for startIndex and endIndex) could be written. In these, we continue towards the center of a string as removable characters are encountered.
Then We take a substring (of the inner part of the string) to perform the trimming operation.
String Substring
Summary. In Swift, strings are manipulated in many ways. With convenient methods like trimmingCharacters, we avoid writing complex logic to eliminate characters.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 20, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen