Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim only trailing whitespace from end of string in Swift 3

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.

like image 596
Jason Sturges Avatar asked Jan 10 '17 09:01

Jason Sturges


People also ask

How do you remove trailing spaces in Swift?

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.

How do you remove whitespace from string ends?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

What method removes only trailing whitespaces from a string?

How to Remove only Trailing Whitespace and Characters from Strings in Python. To remove only trailing whitespace and characters, use the . rstrip() method.


1 Answers

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.

like image 152
Martin R Avatar answered Sep 19 '22 13:09

Martin R