将出现的 NSString 替换为 `'` 到 `\'`

Replace occurrences of NSString with `'` to `\'`

我有一个 NSString,我试图在其中替换特殊字符。我的部分字符串如下所示:

我已将 ' 替换为 \'

NSString *originalString = "a rand'om st'ring"
NSString *resultString = [originalString stringByReplacingOccurrencesOfString:@"'" withString:@"\'"]; 


// "a random string" (output of "po resultString" in LLDB)

使用转义字符“\”,我们可以删除不需要的字符。转义字符 ("\") 旁边的字符将为 ignored/escaped。

NSString *str = @"'Hello'";
str = [str stringByReplacingOccurrencesOfString:@"'" withString:@"\"];

如果您想用 \' 替换 ' 使用

NSString *str = @"ladies'";
str = [str stringByReplacingOccurrencesOfString:@"'" withString:@"\'"];

\ 是一个转义字符,因此您必须使用它两次。

注: \是objective c中的转义符。

 NSString *s = @"This is Testing Mode and we are testing just Details of this Ladies' Market place";


NSString *r = [s stringByReplacingOccurrencesOfString:@"'" withString:@"\'"];