使用NSString将UTF-8编码转换为ISO 8859-1编码

问题描述:

我有一个应用程序从服务器读取UTF-8格式的数据,但它必须显示在ISO 8859-1(拉丁语-1)。是否有任何Cocoa API来实现这一点?

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?

可以使用 NSString getCString:maxLength:encoding: 方法,如下所示:

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);

一旦你有了这个,你可以重新初始化一个 NSString 类方法:

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];