开发者

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 t开发者_如何学编程his 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


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


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];
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜