写在前面:本文旨在解决OC中字符串的编码解码问题,并非是HTML5或者其语言的转码问题。
特殊字符编码解码
Foundation框架
- (NSString *)ocstringEncode:(NSString *)str {
return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%<>[\\]^`{|}\"]+"].invertedSet];
// 在对URL中的中文进行转码时,在iOS 9之前我们使用
// [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 在iOS 9之后使用:
// [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
// NSCharacterSet其他类方法的所代表的特殊字符串
// URLFragmentAllowedCharacterSet @"#%<>[\]^`{|}"
// URLHostAllowedCharacterSet @"#%/<>?@\^`{|}"
// URLPasswordAllowedCharacterSet @"#%/:<>?@[\]^`{|}"
// URLPathAllowedCharacterSet @"#%;<>?[\]^`{|}"
// URLQueryAllowedCharacterSet @"#%<>[\]^`{|}"
// URLUserAllowedCharacterSet @"#%/:<>?@[\]^`"
}
- (NSString *)ocstringDecode:(NSString *)str {
return [str stringByRemovingPercentEncoding];
}
CoreFoundation框架,C语言
- (NSString *)stringEncode {
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), kCFStringEncodingUTF8));
return encodedString;
}
- (NSString *)stringDecode {
NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
特殊字符编码解码举例
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSString *url = @"http://study.minshenglife.com:7100/api/v1/sso?openUser=2Xxad8F+IOEAHrt5K6Lm4w==&openPwd=/luuvx4Q0BQysuMKfE5dMA==曾仕林";
NSString *str1 = [self ocstringEncode:url];
NSString *str2 = [self ocstringDecode:str1];
NSString *str3 = [self stringEncode:url];
NSString *str4 = [self stringDecode:str3];
NSLog(@"\n%@ \n%@ \n%@ \n%@",str1,str2,str3,str4);
}
- (NSString *)ocstringEncode:(NSString *)str {
return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%<>[\\]^`{|}\"]+"].invertedSet];
// 在对URL中的中文进行转码时,在iOS 9之前我们使用
// [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 在iOS 9之后使用:
// [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}
- (NSString *)ocstringDecode:(NSString *)str {
return [str stringByRemovingPercentEncoding];
}
- (NSString *)stringEncode:(NSString *)str {
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("#%<>[\\]^`{|}\"]+"), kCFStringEncodingUTF8));
return encodedString;
}
- (NSString *)stringDecode:(NSString *)str {
NSString *result = [(NSString *)str stringByReplacingOccurrencesOfString:@"+" withString:@" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
打印结果: