Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with a user input string that gives an "unprintable ascii character found in source file" error when pasted into Xcode?

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?

like image 447
webmagnets Avatar asked Apr 14 '15 13:04

webmagnets


2 Answers

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
}
like image 68
Chackle Avatar answered Oct 25 '22 13:10

Chackle


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.

enter image description here

like image 45
Price Ringo Avatar answered Oct 25 '22 12:10

Price Ringo