开发者

How can I decode a utf8 NSstring on iphone?

I have an NSstring that is encoded with UTF8. I want to decode 开发者_如何学Goit.

I tried this but it doesn't work:

NSString *decodedString = [NSString stringWithUTF8String:[encodedString cStringUsingEncoding:[NSString defaultCStringEncoding]]];

How can I do that?

Thanks


Sending cStringUsingEncoding: to encodedString can only work if encodedString is an NSString object. Having an NSString object is the point you're trying to get to. Moreover, that method does not decode the string, it encodes the string using the encoding you ask for; thus, in the code you show, you ask for the (already-encoded) string to be encoded in some random encoding (the default C string encoding), then attempt to decode the result as UTF-8. That won't work.

You don't specify what type you're using for encodedString. Either way, you need to create the NSString object by passing encodedString and its encoding.

  • If encodedString is an NSData object, use the initWithData:encoding: method.
  • If it's a null-terminated C string; use the initWithCString:encoding: method or (only when it's UTF-8) the initWithUTF8String: method.
  • If it's just plain (unterminated) bytes, use the initWithBytes:length:encoding: method.

All of these except initWithUTF8String: require you to specify the encoding (initWithUTF8String: does by definition), and all of them except initWithData:encoding: come in an autoreleasing convenience version (+stringWith… instead of -initWith…).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜