我从 web 服务收到了包含 Unicode 字符的字符串。我想将其转换为普通的 NSString。所以我该怎么做?
例如:“这不是你的自行车”
那么如何删除 unicode 并用其相等的特殊符号替换它。
输出将是:“这不是你的自行车”
我从 web 服务收到了包含 Unicode 字符的字符串。我想将其转换为普通的 NSString。所以我该怎么做?
例如:“这不是你的自行车”
那么如何删除 unicode 并用其相等的特殊符号替换它。
输出将是:“这不是你的自行车”
char cString[] = "This isn\u2019t your bike";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result string: %@", string);
这应该有效。
更新评论:
并非所有字体都支持您指定的 unicode 字符。
http://www.fileformat.info/info/unicode/char/92/fontsupport.htm
但是这个可以。
http://www.fileformat.info/info/unicode/char/2019/fontsupport.htm
这就是它抛出错误的原因。
NSString *final_url = [NSString stringWithFormat:url];
final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:120.0];
NSURLResponse *response;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *objJSON = [SBJSON new];
NSMutableDictionary *objDataDic = [objJSON objectWithString:strResponse error:nil];
有一个库可以转换 https://github.com/alexaubry/HTMLString。它将转换所有类型的 Unicode 字符。
let escapedSnack = "Fish & Chips"
let snack = escapedSnack.removingHTMLEntities // "Fish & Chips"