NSString Backslash escaping

对着背影说爱祢 提交于 2019-12-04 04:30:06

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/2931942/nsstring-backslash-escaping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!