如何将 NSString 编码转换为 UTF8
我做了类似的事情:
NSData *dt = [mystr dataUsingEncoding:NSWindowsCP1251StringEncoding];
NSString *str = [NSString alloc] initWithData:dt encoding:NSUTF8StringEncoding];
then NSLog(@"%@", str);
但是,如果 'mystr' 是英语,那么 NSLog
会按原样打印它,但是如果 mystr
是阿拉伯语(例如)NSLog
将不会打印任何内容,那么如何将 mystr
的编码更改为 UTF8?
I have done something like:
NSData *dt = [mystr dataUsingEncoding:NSWindowsCP1251StringEncoding];
NSString *str = [NSString alloc] initWithData:dt encoding:NSUTF8StringEncoding];
then NSLog(@"%@", str);
However, if 'mystr' is English then the NSLog
would print it as is, but if mystr
is Arabic (for ex.) NSLog
will not print anything, so how can I change the encoding of mystr
to UTF8?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的第一行创建一些采用 cp1251 编码的数据。第二行表示“将此数据读入字符串,假设字节表示 UTF8 编码的字符串”。但由于这些字节表示 cp1251 编码的字符串,因此效果不太好。
NSString 表示字符的有序集合。在内部,它使用某种编码将这些字符存储在内存中,但它的接口提供了对字符串的独立于编码的访问,因此您可以认为 NSString 与编码无关。如果您想要的是表示 UTF8 编码中的字符串的字节集合,那么您不需要 NSString。您想要让 NSString 发出这样的字节集合,也许使用您已经找到的 -dataUsingEncoding: 方法。
Your first line creates some data that is in cp1251 encoding. Your second line says "read this data into a string, assuming that the bytes represent a UTF8 encoded string". But because the bytes represent a cp1251 encoded string, that's not likely to work very well.
NSString represents an ordered collection of characters. Internally it uses some encoding to store these characters in memory, but its interface provides an encoding-independent access to the string and you can therefore consider NSString to be encoding-agnostic. If what you want is a collection of bytes that represent the string in UTF8 encoding, then you don't want an NSString. You want to get an NSString to emit such a collection of bytes, perhaps using the -dataUsingEncoding: method you've already found.
试试这个
Try this one
之后导入,
在您进行编码的地方写入.h文件中,此方法
之后写入.m文件中方法实现,
然后像这样使用
,在这里传递您的字符串
import
after that where u r doing encode write in .h file this method
after that write in .m file method implementation
after that use like this
here pass ur string whatever
您尝试过
[mystr UTF8String]
吗?这将返回一个 char *Did you try
[mystr UTF8String]
? This returns a char *你可以试试这个
1) NSString 到 NSData(NSWindowsCP1251StringEncoding
2) 反转过程。
You can try this
1) NSString to NSData(NSWindowsCP1251StringEncoding
2)Revers process.