To trim a string in Swift, you can use the trimmingCharacters(in:)
method of the String class.
In this example,
str1
with a value of " Hello World "
.trimmingCharacters(in:)
method on str1
with the .whitespaces
option to remove leading and trailing whitespace characters.import Foundation
let str1 = " Hello World "
let trimmedStr1 = str1.trimmingCharacters(in: .whitespaces)
print("Trimmed string is: '\(trimmedStr1)'")
Trimmed string is: 'Hello World'
In this example,
str2
with a value of " apple"
.trimmingCharacters(in:)
method on str2
with the .whitespaces
option to remove leading whitespace characters.import Foundation
let str2 = " apple"
let trimmedStr2 = str2.trimmingCharacters(in: .whitespaces)
print("Trimmed string is: '\(trimmedStr2)'")
Trimmed string is: 'apple'
In this example,
str3
with a value of "banana "
.trimmingCharacters(in:)
method on str3
with the .whitespaces
option to remove trailing whitespace characters.import Foundation
let str3 = "banana "
let trimmedStr3 = str3.trimmingCharacters(in: .whitespaces)
print("Trimmed string is: '\(trimmedStr3)'")
Trimmed string is: 'banana'
In this tutorial, we learned How to Trim a String in Swift language with well detailed examples.