I am working on an app that lets the user paste in text and then the app processes that text.
With a certain text string I am getting an "unprintable ascii character found in source file" error. The unprintable character appears to be a tab, but I'm not sure. Anyway, it is causing problems when I try to process the text.
How can I filter out this or other unprintable characters when I first save the string in a variable?
Or is there another way to deal with this?
Here's another way to do it.
This version also allows new line characters.
func convertString(string: String) -> String {
var data = string.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)
return NSString(data: data!, encoding: NSASCIIStringEncoding) as! String
}
If you are only interested in keeping printable ASCII characters, then this code should work.
extension String {
func printableAscii() -> String {
return String(bytes: filter(self.utf8){$0 >= 32}, encoding: NSUTF8StringEncoding) ?? ""
}
}
Note this will filter tabs and line feeds too which may not be expected. Unprintable ASCII are any values less than 0x20. Here is a Playground screen capture.
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