欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

ios 汉字转码 (汉字与utf8、Unicode转与汉字)

程序员文章站 2024-01-08 12:05:28
Unicode转化为汉字: +(NSString *)replaceUnicode:(NSString*)unicodeStr{ NSString *tempStr1=[u...

Unicode转化为汉字:

+(NSString *)replaceUnicode:(NSString*)unicodeStr{

NSString *tempStr1=[unicodeStrstringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
NSString *tempStr2=[tempStr1stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
NSString *tempStr3=[[@"\""stringByAppendingString:tempStr2]stringByAppendingString:@"\""];
NSData *tempData=[tempStr3dataUsingEncoding:NSUTF8StringEncoding];
NSString* returnStr =[NSPropertyListSerializationpropertyListFromData:tempData
mutabilityOption:NSPropertyListImmutable
format:NULL
errorDescription:NULL];

return [returnStrstringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}

 

汉字与utf8相互转化:

NSString* strA =[@"%E4%B8%AD%E5%9B%BD"stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *strB=[@"中国"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 

NSString 转化为utf8:

NSString *strings=[NSStringstringWithFormat:@"abc"];

NSLog(@"strings :%@",strings);

CF_EXPORT
CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator,CFStringReforiginalString,CFStringRef charactersToLeaved, CFStringReflegalURLCharactersToBeEscaped,CFStringEncoding encoding);

NSString *encodedValue=(__bridge NSString*)CFURLCreateStringByAddingPercentEscapes(nil,(__bridgeCFStringRef)strings,nil,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8);

 

iso8859-1 到 unicode编码转换:

+(NSString *)changeISO88591StringToUnicodeString:(NSString*)iso88591String
{

NSMutableString *srcString=[[[NSMutableString alloc]initWithString:iso88591String]autorelease];

[srcString replaceOccurrencesOfString:@"&" withString:@"&" options:NSLiteralSearchrange:NSMakeRange(0,[srcString length])];
[srcString replaceOccurrencesOfString:@"&#x" withString:@"" options:NSLiteralSearchrange:NSMakeRange(0,[srcString length])];

NSMutableString *desString=[[[NSMutableString alloc]init] autorelease];

NSArray *arr=[srcString componentsSeparatedByString:@";"];

for(int i=0;i<[arr count]-1;i++){

NSString *v=[arr objectAtIndex:i];
char *c= malloc(3);
int value =[StringUtil changeHexStringToDecimal:v];
c[1]= value &0x00FF;
c[0]= value >>8&0x00FF;
c[2]='\0';
[desString appendString:[NSString stringWithCString:c encoding:NSUnicodeStringEncoding]];
free(c);
}

return desString;
}