views:

4056

answers:

6

Say I have an NSString (or NSMutableString) containing:

I said "Hello, world!".
He said "My name's not World."

What's the best way to turn that into:

I said \"Hello, world!\".\nHe said \"My name\'s not World.\"

Do I have to manually use -replaceOccurrencesOfString:withString: over and over to escape characters, or is there an easier way? These strings may contain characters from other alphabets/languages.

How is this done in other languages with other string classes?

+4  A: 

I don't think there is any built-in method to "escape" a particular set of characters.

If the characters you wish to escape is well-defined, I'd probably stick with the simple solution you proposed, replacing the instances of the characters crudely.

Be warned that if your source string already has escaped characters in it, then you'll probably want to avoid "double-escaping" them. One way of achieving this would be to go through and "unescape" any escaped character strings in the string before then escaping them all again.

If you need to support a variable set of escaped characters, take a look at the NSScanner methods "scanUpToCharactersFromSet:intoString:" and "scanCharactersFromSet:intoString:". You could use these methods on NSScanner to cruise through a string, copying the parts from the "scanUpTo" section into a mutable string unchanged, and copying the parts from a particular character set only after escaping them.

danielpunkass
It's a lot more complicated than I thought it would ever have to be, but it does the job well.
dreamlax
A: 

You might even want to look into using a regex library (there are a lot of options available, RegexKit is a popular choice). It shouldn't be too hard to find a pre-written regex to escape strings that handles special cases like existing escaped characters.

Marc Charbonneau
A: 

This will escape double quotes in NSString:

NSString *escaped = [originalString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

So you need to be careful and also escape the escape character...

Jussi Niinikoski
+1  A: 

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

Niklas Alvaeus
A: 

Do this:

NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
    (CFStringRef)unencodedString,
    NULL,
    (CFStringRef)@"!*'();:@&=+$,/?%#[]",
    kCFStringEncodingUTF8 );

Reference: http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/

fursund
Those are percent escapes, I want backslash escapes.
dreamlax