ios 在 Swift 中解码一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28310589/
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
Decode a string in Swift
提问by Kevinvs
How can I decode a string in swift? The string is now test%2Enl
, but the correct format is test.nl
.
如何快速解码字符串?字符串现在是test%2Enl
,但正确的格式是test.nl
。
I now have this:
我现在有这个:
let encodedData = encodedString.dataUsingEncoding(NSUTF16StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
return attributedString.string
回答by Christian
You can use stringByReplacingPercentEscapesUsingEncoding
您可以使用 stringByReplacingPercentEscapesUsingEncoding
var properString = s.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
Update for swift 3:Use removingPercentEncoding
instead.
swift 3 的更新:removingPercentEncoding
改为
使用。
回答by TenaciousJay
In Swift 3:
在 Swift 3 中:
let encodedString = "test%2Enl"
let decodedString = encodedString.removingPercentEncoding!
Swift 3 removed a lot of "excess" wording in many of the Apple APIs.
Swift 3 在许多 Apple API 中删除了很多“多余”的措辞。
In this case stringByRemovingPercentEncoding was simplified to removingPercentEncoding.
在这种情况下,stringByRemovingPercentEncoding 被简化为removingPercentEncoding。
回答by Jeremy Pope
Or you can use stringByRemovingPercentEncoding
?
或者你可以使用stringByRemovingPercentEncoding
?
From the docs:
从文档:
Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
通过用匹配的 UTF-8 字符替换所有百分比编码序列,返回从接收器生成的新字符串。
let encodedString = "test%2Enl"
let decodedString = encodedString.stringByRemovingPercentEncoding!
println(decodedString)
This would print test.nl
这将打印 test.nl
回答by eurobrew
You could use SwiftString (https://github.com/amayne/SwiftString) to do this.
您可以使用 SwiftString ( https://github.com/amayne/SwiftString) 来执行此操作。
"test%2Enl".decodeHTML() // "test.nl"
DISCLAIMER: I wrote this extension
免责声明:我写了这个扩展