Start learning free

LESSON 65 OF 678 · STRINGS I

String Strip / Trim in Swift

Lesson

In Swift, you can remove leading and trailing whitespace from a string using trimmingCharacters(in:), which comes from Foundation, so a standalone file needs import Foundation at the top:

s.trimmingCharacters(in: .whitespaces)              // removes leading and trailing whitespace
s.trimmingCharacters(in: .whitespacesAndNewlines)   // removes whitespace and newlines from both ends

Here are some examples:

import Foundation

let s = "  hello  "
print(s.trimmingCharacters(in: .whitespaces))              // "hello"
print(s.trimmingCharacters(in: .whitespacesAndNewlines))   // "hello"

These methods return a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and strip whitespace from text!


Hint
Use text.trimmingCharacters(in: .whitespaces) and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check