服务器返回由urlencode函数处理的gb2312字符串:
%D7%CF%BD%FB%B3%C7%C4%A7%D6%E4_%CE%DE%CF%DE%D0%A1%CB%B5%CD%F8_www.55x.cn.rar
如何将其解码回gb2312字符串:
紫禁城魔咒_无限小说网_www.55x.cn.rar
发布于 2017-01-05 05:14:05
在最近的www世界中,对其他编码的百分比编码(而不是UTF-8 )并不被认为是一种推荐的方法,因此您可能需要自己实现这种转换。
可能是这样的:
extension String.Encoding {
static let gb_18030_2000 = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)))
}
extension String {
func bytesByRemovingPercentEncoding(using encoding: String.Encoding) -> Data {
struct My {
static let regex = try! NSRegularExpression(pattern: "(%[0-9A-F]{2})|(.)", options: .caseInsensitive)
}
var bytes = Data()
let nsSelf = self as NSString
for match in My.regex.matches(in: self, range: NSRange(0..<self.utf16.count)) {
if match.rangeAt(1).location != NSNotFound {
let hexString = nsSelf.substring(with: NSMakeRange(match.rangeAt(1).location+1, 2))
bytes.append(UInt8(hexString, radix: 16)!)
} else {
let singleChar = nsSelf.substring(with: match.rangeAt(2))
bytes.append(singleChar.data(using: encoding) ?? "?".data(using: .ascii)!)
}
}
return bytes
}
func removingPercentEncoding(using encoding: String.Encoding) -> String? {
return String(data: bytesByRemovingPercentEncoding(using: encoding), encoding: encoding)
}
}
let origStr = "%D7%CF%BD%FB%B3%C7%C4%A7%D6%E4_%CE%DE%CF%DE%D0%A1%CB%B5%CD%F8_www.55x.cn.rar"
print(origStr.removingPercentEncoding(using: .gb_18030_2000)) //->Optional("紫禁城魔咒_无限小说网_www.55x.cn.rar")发布于 2021-02-10 14:09:06
NSString确实将此功能包含在不推荐的函数中。
https://developer.apple.com/documentation/foundation/nsstring/1407783-replacingpercentescapes
发布于 2022-11-23 03:15:37
奥珀的回答很棒。最近我也遇到了这个问题,并找到了这篇文章。我想出了一个函数来做倒置手术。希望它能帮到别人。
func urlencode(using encoding: String.Encoding = .gb_18030_2000) -> String? {
var res = ""
let allowedSet = NSMutableCharacterSet()
allowedSet.formUnion(with:CharacterSet.urlQueryAllowed)
// I need to filter the `&` char as well. change it for your needs.
allowedSet.removeCharacters(in: "&")
let allowed = allowedSet as CharacterSet
if let data = src.data(using: encoding) {
res = data.reduce(into:res) {
let scalar = UnicodeScalar($1)
if $1 <= 127, allowed.contains(scalar) {
$0 += String(Character(scalar))
} else {
$0 += String(format:"%%%02X", $1)
}
}
}
return res.isEmpty ? self : res
}https://stackoverflow.com/questions/41477013
复制相似问题