How can I remove the whitespace character set from a string but keep the single spaces between words. I would like to remove double spaces and triple spaces, etc...
相关问题
- how to split a list into a given number of sub-lis
- “Zero out” sensitive String data in Swift
- Generate string from integer with arbitrary base i
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
相关文章
- JSP String formatting Truncate
- Using if let syntax in switch statement
- Selecting only the first few characters in a strin
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Python: print in two columns
Another option is to use regular expression search to replace all occurrences of one or more whitespace characters by a single space. Example (Swift 3):
For swift 3.1
Will output :
Swift 2 compatible code:
Usage:
Swift 3
Legacy Swift
NSCharacterSet
makes this easy:or if you'd like it as a
String
extension:All credit to the NSHipster post on NSCharacterSet.
When you have an Objective-C/Foundation background, it may seem obvious to use
componentsSeparatedByCharactersInSet(:)
with Swift in order to trim your string from its redundant whitespace characters.The steps here are to get from your string an array of
String
where all whitespace characters have been replaced by empty strings, to filter this array into a new array ofString
where all empty strings have been removed and to join all the strings of this array into a new string while separating them by a whitespace character.The following Playground code shows how to do it this way:
If you need to repeat this operation, you can refactor your code into a
String
extension:However, with Swift, there is another way that is really functional and that does not require you to import
Foundation
.The steps here are to get from your string an array of
String.CharacterView
where all whitespace characters have been removed, to map this array ofString.CharacterView
to an array ofString
and to join all the strings of this array into a new string while separating them by a whitespace character.The following Playground code shows how to do it this way:
If you need to repeat this operation, you can refactor your code into a
String
extension:You can use the trim() method in a Swift String extension I wrote https://bit.ly/JString.