ios 漢字轉碼 (漢字與utf8、Unicode轉與漢字
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;
}