【问题标题】:Convert Unicode character to NSString将 Unicode 字符转换为 NSString
【发布时间】:2012-08-23 11:31:17
【问题描述】:

我从 web 服务收到了包含 Unicode 字符的字符串。我想将其转换为普通的 NSString。那我该怎么做呢?

例如:“这不是你的自行车”

那么如何删除 unicode 并用其相等的特殊符号替换它。

输出将是:“这不是你的自行车”

【问题讨论】:

标签: iphone utf-8 unicode-string


【解决方案1】:
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

这就是它抛出错误的原因。

【讨论】:

  • 当我尝试使用相同的代码时,它会提示我出现“无效的通用字符”之类的错误
  • 您使用了错误的 unicode。我已经用正确的撇号 unicode 更新了答案。请检查
  • 不,它不是一个错误的 Unicode。请查看fileformat.info/info/unicode/char/92/index.htm ...
  • 该错误与字体无关,而是与 C 语言以及它如何允许形成字符串文字有关。 C99 在 6.4.3.2 中规定:“通用字符名称不得指定短标识符小于 00A0 的字符”。
【解决方案2】:
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];

【讨论】:

    【解决方案3】:

    有一个库可以进行转换 https://github.com/alexaubry/HTMLString。它将转换所有类型的 Unicode 字符。

    let escapedSnack = "Fish & Chips"
    let snack = escapedSnack.removingHTMLEntities // "Fish & Chips" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多