How can I trim the leading from text

Asked on 07/30/2024

1 search

To trim the leading whitespace from text in Swift, you can use the trimmingCharacters(in:) method. Here's an example:

let originalString = "   Hello, World!   "
let trimmedString = originalString.trimmingCharacters(in: .whitespaces)
print(trimmedString) // "Hello, World!"

This method removes the leading and trailing whitespace characters from the string. If you only want to remove the leading whitespace, you can use a combination of drop(while:) and CharacterSet.whitespaces:

let originalString = "   Hello, World!   "
let trimmedLeadingString = String(originalString.drop(while: { $0.isWhitespace }))
print(trimmedLeadingString) // "Hello, World!   "

For more advanced text handling, you might want to look into sessions like Build multilingual-ready apps and Create custom visual effects with SwiftUI from WWDC 2024, which discuss various text manipulation techniques and considerations.