Start learning free

LESSON 64 OF 349 · STRINGS I

String Strip / Trim in Swift in Swift

Lesson

In Swift, you can remove leading and trailing whitespace from a string using trimmingCharacters(in:):

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

Here are some examples:

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 s!


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

STEP 1 OF 1
    Ctrl + Enter to check

    String Strip in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free