如何处理在粘贴到 Xcode 时出现“在源文件中发现无法打印的 ascii 字符”错误的用户输入字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29628813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to deal with a user input string that gives an "unprintable ascii character found in source file" error when pasted into Xcode?
提问by webmagnets
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.
对于某个文本字符串,我收到“在源文件中发现的无法打印的 ascii 字符”错误。不可打印的字符似乎是制表符,但我不确定。无论如何,当我尝试处理文本时,它会引起问题。
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?
或者有其他方法可以解决这个问题吗?
采纳答案by Chackle
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
}
回答by Price Ringo
If you are only interested in keeping printable ASCII characters, then this code should work.
如果您只对保留可打印的 ASCII 字符感兴趣,那么此代码应该可以工作。
extension String {
func printableAscii() -> String {
return String(bytes: filter(self.utf8){##代码## >= 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.
请注意,这也将过滤可能出乎意料的选项卡和换行符。不可打印的 ASCII 是任何小于 0x20 的值。这是一个 Playground 屏幕截图。