iOS涓紪鐮佽浆鍖�
1.UTF-8杞寲
NSString *data = @"浣犲ソ锛屽寳浜紒";
//杞崲鎴怳TF-8
NSString *dataUTF8 = [data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",dataUTF8);
//UTF-8杞珿BK,灏哢TF8浠g爜鏇挎崲锛屽畼鏂硅В閲婂涓嬨��
//Replaces all percent escapes with the matching characters as determined by the given encoding.聽 Returns nil if the transformation is not possible (i.e. the percent escapes give a byte sequence not legal in the given encoding).聽 See CFURLCreateStringByReplacingPercentEscapes in CFURL.h for more complex transformations
NSString *dataGBK = [dataUTF8 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",dataGBK);
//Unicode杞琔TF-8+ (NSString *)encodeToPercentEscapeString: (NSString *) input聽 {聽 聽 聽 // Encode all the reserved characters, per RFC 3986聽 聽 聽 // ()
NSString *outputStr = (NSString *)
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)input,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
return outputStr;
}
+ (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
NSMutableString *outputStr = [NSMutableString stringWithString:input];
[outputStr replaceOccurrencesOfString:@"+"
withString:@" "
options:NSLiteralSearch
range:NSMakeRange(0, [outputStr length])];
return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
2.UTF-8鍜孶nicode杞寲
//Unicode杞琔TF-8
+ (NSString*) replaceUnicode:(NSString*)aUnicodeString
{
NSString *tempStr1 = [aUnicodeString stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
mutabilityOption:NSPropertyListImmutable
format:NULL
errorDescription:NULL];
return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}
+(NSString *) utf8ToUnicode:(NSString *)string
{
NSUInteger length = [string length];
NSMutableString *s = [NSMutableString stringWithCapacity:0];
for (int i = 0;i < length; i++)
{
unichar _char = [string characterAtIndex:i];
//鍒ゆ柇鏄惁涓鸿嫳鏂囧拰鏁板瓧
if (_char <= '9' && _char >= '0')
{
[s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
}
else if(_char >= 'a' && _char <= 'z')
{
[s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
}
else if(_char >= 'A' && _char <= 'Z')
{
[s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
}
else
{
[s appendFormat:@"\\u%x",[string characterAtIndex:i]];
}
}
return s;
}