Swift String trimmingCharacters()

The trimmingCharacters() method removes whitespace from both ends of a string.

Example

var message = "   Swift is fun    "

// remove leading and trailing whitespaces var newMessage = message.trimmingCharacters(in: .whitespaces)
print(newMessage) // Output: Swift is fun

trimmmingCharacters() Syntax

The syntax of trimmingCharacters() is:

string.trimmingCharacters(in: .whitespaces)

Here, string is an object of the String class.


trimmingCharacters() Parameter

The trimmingCharacters() method takes one parameter:

  • whitespaces - a property that removes whitespaces from both ends of a string

trimCharacters() Return Value

The trimmingCharacters() method returns:

  • a string with whitespaces removed from both ends of the string

Note: In programming, whitespace is any character or series of characters that represent horizontal or vertical space. For example: space, newline \n, tab \t, etc.


Example: Swift trimmingCharacters()

var str1 = "     Learn  Swift Programming "
var str2 = "Learn \nSwift Programming\n\n   "

print(str1.trimmingCharacters(in: .whitespaces)) print(str2.trimmingCharacters(in: .whitespaces))

Output

Learn  Swift Programming
Learn 
Swift Programming

In this program,

  • str1.trimmingCharacters(in: .whitespaces) returns "Learn Swift Programming"
  • str2.trimmingCharacters(in: .whitespaces) returns "Learn \nSwift Programming"

As you can see from the above example, the trimmingCharacters() method only removes the leading and trailing whitespace. It doesn't remove whitespace that appears in the middle.