开发者

Escaping backslashes in method call stringByReplacingOccurrencesOfString Does not work in Objective C

开发者 https://www.devze.com 2022-12-10 05:33 出处:网络
This line of code does not produce the result I am expecting. NSString *tmpstoryTitle2 = [tmpstoryTitle stringByReplacingOccurrencesOfString:@\"\\\"\" withString:@\"\\\\\\\"\"];

This line of code does not produce the result I am expecting.

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

I am attempting to change a string like this:

hello, "this" is my string.

to

hello, \"this\" is my string.

With the code above. However, the output I get is:

hello, \\"this\\" is my string.

If I remove the \\ from the search string \\" to replace \" I get the output:

hello, "this" is my string.

Which is right, but I am unable to add the \ infront of my " with the escape sequence, \\ for backslash and \" for d开发者_高级运维ouble quotes.


How are you verifying the string? If you print it to the console (using NSLog()), those leading backslashes will be inserted for you; try setting a UILabel's text to it, and see if it shows up that way. Your code looks correct.


Are you sure you source string (tmpstoryTitle) does not contain slash already? I just tried

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

And it produces:

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.

Which is seems like what you expect?

0

精彩评论

暂无评论...
验证码 换一张
取 消