Jack
Jack

Reputation: 3878

NSString Backslash escaping

I am working on an iPhone OS application that sends an xml request to a webservice. In order to send the request, the xml is added to an NSString. When doing this I have experienced some trouble with quotation marks " and backslashes \ in the xml file, which have required escaping. Is there a complete list of characters that need to be escaped?

Also, is there an accepted way of doing this escaping (ie replacing \ with \\ and " with \") or is it a case of creating a method myself?

Thanks

Upvotes: 3

Views: 9946

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52227

You can use a NSScanner that will scan for characters from a character set and if found, it will add the escaping \\ to a new string and copy the next substring from the found special character till the next.

NSString *sourceString = /* Some input String*/;
NSMutableString *destString = [@"" mutableCopy];
NSCharacterSet *escapeCharsSet = [NSCharacterSet characterSetWithCharactersInString:@" ()\\"];

NSScanner *scanner = [NSScanner scannerWithString:sourceString];
while (![scanner isAtEnd]) {
    NSString *tempString;
    [scanner scanUpToCharactersFromSet:escapeCharsSet intoString:&tempString];
    if([scanner isAtEnd]){
        [destString appendString:tempString];
    }
    else {
        [destString appendFormat:@"%@\\%@", tempString, [sourceString substringWithRange:NSMakeRange([scanner scanLocation], 1)]];
        [scanner setScanLocation:[scanner scanLocation]+1];
    }
}

Upvotes: 1

Jonny Cook
Jonny Cook

Reputation: 684

NSString *escapedString = [unescapedString stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
escapedString = [escapedString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

Doesn't fully answer your question, but seems like it might help with the second part...

Upvotes: 5

Related Questions