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