在方法调用中转义反斜杠stringByReplacingOccurrencesOfString在Objective C中不起作用

时间:2009-11-02 20:18:00

标签: iphone objective-c

这行代码不会产生我期望的结果。

NSString *tmpstoryTitle2 = [tmpstoryTitle stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

我正在尝试更改这样的字符串:

你好,“这个”是我的字符串。

你好,\“这个是我的字符串。

使用上面的代码。但是,我得到的输出是:

你好,\\“这个\\”是我的字符串。

如果我从搜索字符串\\“中删除\\”替换\“我得到输出:

你好,“这个”是我的字符串。

哪个是对的,但是我无法添加“带有转义序列的\”前面的\,反斜杠和\“双引号”。

2 个答案:

答案 0 :(得分:1)

您确定源字符串( tmpstoryTitle )是否已包含斜杠?我刚试过

NSString * tmpstoryTitle = [[NSString alloc] initWithString: @"hello, \"this\" is my string."];
NSString * tmpstoryTitle2 = [tmpstoryTitle stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
NSLog(@"%@", tmpstoryTitle);
NSLog(@"%@", tmpstoryTitle2);

它产生:

2009-11-02 22:32:40.756 JezzBall[71173:207] hello, "this" is my string.
2009-11-02 22:32:40.767 JezzBall[71173:207] hello, \"this\" is my string.

这看起来像你期望的那样?

答案 1 :(得分:1)

你是如何验证字符串的?如果将其打印到控制台(使用NSLog()),将为您插入那些前导反斜杠;尝试将UILabel的文本设置为它,并查看它是否以这种方式显示。您的代码看起来是正确的。