将UTF-8编码的NSData转换为NSString [英] Convert UTF-8 encoded NSData to 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:
以避免额外的 \0
。
If the data is null-terminated, you should instead use -stringWithUTF8String:
to avoid the extra \0
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 \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))
这篇关于将UTF-8编码的NSData转换为NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!