我正在尝试使用Swift编码和解码字符串和数据。
在Java中,它相对简单,我可以像下面的代码片段一样使用Charset CharsetDecoder CharsetEncoder
我认为解决方案是使用String.Encoding,但是如何?

public static void Test() throws CharacterCodingException {
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder chdecoder = charset.newDecoder();
    CharsetEncoder chencoder = charset.newEncoder();
    String s = "Encode and Decode Example.";
    if(!chencoder.canEncode((char) 9)) return;//not here but i need this method
    ByteBuffer byteBuffer= ByteBuffer.wrap(s.getBytes());
    CharBuffer charBuffer = chdecoder.decode(byteBuffer);
    ByteBuffer newByteBuff = chencoder.encode(charBuffer);
    while(newByteBuff.hasRemaining()){
        char ch = (char) newByteBuff.get();
        System.out.print(ch);
    }
    newByteBuff.clear();
}

最佳答案

let str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded =      utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
println("Encoded:  \(base64Encoded)")
if let base64Decoded = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions(rawValue: 0))
                      .map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
{
    // Convert back to a string
    println("Decoded:  \(base64Decoded)")
}
}

关于java - 快速解码和编码字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39938814/

10-13 09:38