Convert UTF-8 encoding to ISO 8859-1 encoding with NSString

为君一笑 提交于 2019-11-28 00:37:41

问题


I have an application that reads the data in UTF-8 format from the server, but it has to be displayed in ISO 8859-1(Latin-1). Are there any Cocoa APIs to achieve this?


回答1:


You can use NSString's getCString:maxLength:encoding: method, like this:

char converted[([string length] + 1)];
[string getCString:converted maxLength:([string length] + 1) encoding: NSISOLatin1StringEncoding];

NSLog(@"%s", converted);

Once you have this, you can then re-initialize an NSString instance from that same encoding using the stringWithCString:encoding: class method:

NSString *converted_str = [NSString stringWithCString:converted encoding:NSISOLatin1StringEncoding];



回答2:


I prefer using dataUsingEncoding:allowLossyConversion: because it doesn't require you to guess how much storage to allocate, and the returned NSData tells you how many bytes were required.




回答3:


Jacobs answer didn't really work for my. What did eventually work for me was to only use

[username stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]



回答4:


use

+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc

Example:

latinStringForDisplay = [NSString stringWithCString:yourCstringHere encoding:NSISOLatin1StringEncoding];

That should do it.



来源:https://stackoverflow.com/questions/4553388/convert-utf-8-encoding-to-iso-8859-1-encoding-with-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!