xiashulin 2010-12-30
iPhone的NSString并不支持ansi的字符串(比如咱们常用的gb2312), 因此如果要读取的话, 需要转换为UTF-8的
而iPhone上自带了libiconv库,于是这个转换变的就比较简单了
首先在工程的Framework部分加入/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/lib/libiconv.dylib
当然,中间那个iPhoneOS3.0.sdk需要换成你当前使用的SDK版本
实际转换过程也就4步.
1,引入iconv库并添加头文件
2,利用iconv_open设置from和to的字符串编码
3,执行iconv进行转换
4,利用iconv_close关闭iconv_open创建的实例.
基本上就是下面的代码片段中 code_convert中的逻辑了.#include <iconv.h> int code_convert(char *from_charset, char *to_charset, char *inbuf, size_t inlen, char *outbuf, size_t outlen) { iconv_t cd = NULL; cd = iconv_open(to_charset, from_charset); if(!cd) return -1; memset(outbuf, 0, outlen); if(iconv(cd, &inbuf, &inlen, &outbuf, &outlen) == -1) return -1; iconv_close(cd); return 0; } int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen); } int g2u(char *inbuf, size_t inlen, char *outbuf,size_t outlen) { return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen); }
而在实际应用时, 无论从文件或者网络读取, 都要获取成NSData或者char *或void *, 至少不能是NSString, 因为NSString无法直接处理.以获取成NSData为例.
+ (NSString *)getANSIString:(NSData *)ansiData { char *ansiString = [ansiData bytes]; int ansiLen = [ansiData length]; int utf8Len = ansiLen * 2; //其实*1.5基本就够了 char *utf8String = (char *)malloc(utf8Len); memset(utf8String, 0, utf8Len); //虽然code_convert中也memset了, 但还是自己分配后就set一次比较好 int result = code_convert("gb2312", "utf-8", ansiString, ansiLen, utf8String, utf8Len); if(result == -1) { free(utf8String); return nil; } NSString *retString = [NSString stringWithUTF8String:utf8String]; free(utf8String); return retString; }
下面方法也可行:
NSStringEncoding myEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSString* postStr = [NSString stringWithFormat:@"isbn=%@",ISBNStr]; NSData* postData = [postStr dataUsingEncoding:myEncoding];