代码之家  ›  专栏  ›  技术社区  ›  Thomas Joulin

在iOS中使用stringbyreplacingoccurrencessofstring:widthString转义单引号时出现问题

  •  6
  • Thomas Joulin  · 技术社区  · 14 年前
     NSString *test =  @"d'escape";
     NSLog(@"%@", [test stringByReplacingOccurrencesOfString:@"'" withString:@"\'"]);
    

    给我打印这个

    2010-10-25 15:10:54.833 MyApp[7136:207] d'escape
    

    我做错什么了?我想得到这个:

    2010-10-25 15:10:54.833 MyApp[7136:207] d\'escape
    
    1 回复  |  直到 14 年前
        1
  •  18
  •   kennytm    14 年前

    \ 它本身是C语言中的一个特殊字符。你需要在源代码中转义它。

    [test stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"]
    //                                                           ^^