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.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
