将 UTF-8 编码的 NSData 转换为 NSString [英] Convert UTF-8 encoded NSData to NSString

查看:31
本文介绍了将 UTF-8 编码的 NSData 转换为 NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自 Windows 服务器的 UTF-8 编码的 NSData,我想将它转换为 iPhone 的 NSString.由于数据包含在两个平台上具有不同值的字符(如度数符号),如何将数据转换为字符串?

I have UTF-8 encoded NSData from windows server and I want to convert it to NSString for iPhone. Since data contains characters (like a degree symbol) which have different values on both platforms, how do I convert data to string?

推荐答案

如果数据不是空终止的,你应该使用 -initWithData:encoding:

If the data is not null-terminated, you should use -initWithData:encoding:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

如果数据以空值结尾,则应改为使用 -stringWithUTF8String: 以避免在末尾出现额外的 .

If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra at the end.

NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];

(请注意,如果输入的 UTF-8 编码不正确,您将得到 nil.)

(Note that if the input is not properly UTF-8-encoded, you will get nil.)

let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.

如果数据以空字符结尾,您可以采用安全的方法,即删除该空字符,或者采用类似于上述 Objective-C 版本的不安全方法.

If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.

// safe way, provided data is -terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is -terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))

这篇关于将 UTF-8 编码的 NSData 转换为 NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆