Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to escape characters like newline and double-quote in NSString

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?

like image 846
dreamlax Avatar asked Feb 23 '09 22:02

dreamlax


2 Answers

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

like image 140
Niklas Alvaeus Avatar answered Oct 06 '22 23:10

Niklas Alvaeus


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.

like image 34
danielpunkass Avatar answered Oct 07 '22 00:10

danielpunkass