2022-11-01 增加Swift版
public extension String {
/// 编码类型
enum Encode {
case unicode
}
/// 字符串编码
/// - Parameter using: 编码类型
func encode(_ using: Encode) -> String? {
switch using {
case .unicode: return utf16.map({ String(format:"\\U%04x", $0) }).joined()
}
return nil
}
/// 字符串解码
/// - Parameter using: 编码类型
func decode(_ using: Encode) -> String? {
switch using {
case .unicode:
let text = "\"" + replacingOccurrences(of: "\\u", with: "\\U") + "\""
if let date = text.data(using: .utf8) {
do {
let result = try PropertyListSerialization.propertyList(
from: date,
options: .mutableContainers,
format: nil
)
return result as? String
} catch {
print(error)
}
}
}
return nil
}
}
//编码 (该方法编码了所有内容,包括字母和数字)
- (NSString *)encodeUnicode {
if (MONull(self)) {
return nil;
}
NSMutableString *string = [[NSMutableString alloc] init];
for (int i = 0; i < self.length; i++) {
unichar _char = [self characterAtIndex:i];
//不足4为左边补0,避免解码错误
NSString *str = [NSString stringWithFormat:@"%04x", _char];
[string appendFormat:@"\\u%@", str];
}
return string;
}
//解码
- (NSString *)decodeUnicode {
if (MONull(self)) {
return nil;
}
const char *charString = self.UTF8String;
NSData *data = [NSData dataWithBytes:charString length:strlen(charString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];
return string;
}