NSString backslash

I am working on an iPhone OS application that sends an xml request to a web service. To send a request, xml is added to NSString. In doing so, I ran into some problems with quotes "and backslashes \in the xml file that require escaping. Is there a complete list of characters to be escaped?

There is also an acceptable way to perform this shielding (i.e. replacing \with \\and "by \") or is this a case of creating a method yourself?

thank

+3
source share
2 answers
NSString *escapedString = [unescapedString stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
escapedString = [escapedString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

, , ...

+5

NSScanner, , , escaping \\ .

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

Source: https://habr.com/ru/post/1747608/


All Articles