将字符串转换为 UTF8String - Swift - iOS - XMLParser

Convert String to UTF8String - Swift - iOS - XMLParser

我有这个字符串 -

&to[]=0532332028&to[]=0532332027

我想将此字符串转换为 (UTF8) -

%26to%5B%5D%3D0532332028%26to%5B%5D%3D0532332027

我已经尝试过此代码 -

let str = String(UTF8String: "&to[]=0532332028&to[]=0532332027".cStringUsingEncoding(NSUTF8StringEncoding)!)

谢谢

要将字符串转成UTF8,可以按照代码

    let text = "&to[]=0532332028&to[]=0532332027"
    let encodeText = text.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    print("encodeText : \(encodeText)")

输出: encodeText : &to%5B%5D=0532332028&to%5B%5D=0532332027

但是通过上面的代码,你不会得到"&"的%26,如果你想要的话 您可以创建自定义方法,使用“stringByReplacingOccurrencesOfString”方法将“&”替换为“%26”。

希望对您有所帮助。

尝试使用此代码:

let text = "&to[]=0532332028&to[]=0532332027"
let output = text.addingPercentEncoding(withAllowedCharacters: .alphanumerics)

输出:

"%26to%5B%5D%3D0532332028%26to%5B%5D%3D0532332027"