Every example of trimming strings in Swift remove both leading and trailing whitespace, but how can only trailing whitespace be removed?
For example, if I have a string:
" example "
How can I end up with:
" example"
Every solution I've found shows trimmingCharacters(in: CharacterSet.whitespaces)
, but I want to retain the leading whitespace.
RegEx is a possibility, or a range can be derived to determine index of characters to remove, but I can't seem to find an elegant solution for this.
To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
How to Remove only Trailing Whitespace and Characters from Strings in Python. To remove only trailing whitespace and characters, use the . rstrip() method.
With regular expressions:
let string = " example " let trimmed = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) print(">" + trimmed + "<") // > example<
\s+
matches one or more whitespace characters, and $
matches the end of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With