gpt4 book ai didi

java - Swift 解码和编码字符串

转载 作者:行者123 更新时间:2023-11-30 13:00:20 28 4
gpt4 key购买 nike

我正在尝试使用 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 - Swift 解码和编码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39938814/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com