-1

In my app I have a text field, and when the user presses a button the text he have entered is added to a label. The problem is that if the user add an space at the end, the txt of the label looks bad.

Text field: "Diego " Label: Great Diego !

2 Answers2

3

Perform this on your String:

let trimmedString = yourstring.trimmingCharacters(in: .whitespacesAndNewlines)

It returns a new string made by removing from both ends of the String characters contained in a given character set, which in this case are whitesspaces and newlines. If you don't want to trim newlines, replace .whitespaceAndNewLines with .whitespace.

Papershine
  • 4,995
  • 2
  • 24
  • 48
2

You can use String's trimming method passing in the characters to be trimmed. One way to do this is:

let string = "   something "
string.trimmingCharacters(in: .whitespacesAndNewlines)

Which will remove whitespace and newlines from the beginning and the end of the string.

Abizern
  • 146,289
  • 39
  • 203
  • 257