views:

212

answers:

2

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 double quotes.

+1  A: 

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?

Aleksei Potov
+1  A: 

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.

Ben Gottlieb
I was hovering over the variable at a break point and IT was correct as, \\". When I did the NSLog it evaluated the \" into ". The hover does not evaluate escape sequences I guess.
Robert
You also need to make sure you're doing `NSLog(@"%@", str)` and not `NSLog(str)`.
Wevah