NSScanner Remove Substring Quotation from NSString

1.6k views Asked by At

I have NSString's in the form of Johnny likes "eating" apples. I want to remove the quotations from my strings so that.

Johnny likes "eating" apples

becomes

John likes apples

I've been playing with NSScanner to do the trick but I'm getting some crashes.

- (NSString*)clean:(NSString*) _string
{   
   NSString *string = nil;
   NSScanner *scanner = [NSScanner scannerWithString:_string];
   while ([scanner isAtEnd] == NO)  
   {
      [scanner scanUpToString:@"\"" intoString:&string];
      [scanner scanUpToString:@"\"" intoString:nil];
      [scanner scanUpToString:@"." intoString:&string]; // picked . becuase it's not in the string, really just want rest of string scanned
   }
   return string;
}
1

There are 1 answers

1
Guillaume On BEST ANSWER

This code is hacky, but seems to produce the output you want.
It was not tested with unexpected inputs (string not in the form described, nil string...), but should get you started.

- (NSString *)stringByStrippingQuottedSubstring:(NSString *) stringToClean
{   
    NSString *strippedString,
             *strippedString2;

    NSScanner *scanner = [NSScanner scannerWithString:stringToClean];

    [scanner scanUpToString:@"\"" intoString:&strippedString];                          // Getting first part of the string, up to the first quote
    [scanner scanUpToString:@"\" " intoString:NULL];                                    // Scanning without caring about the quoted part of the string, up to the second quote

    strippedString2 = [[scanner string] substringFromIndex:[scanner scanLocation]];     // Getting remainder of the string

    // Having to trim the second part of the string
    // (Cf. doc: "If stopString is present in the receiver, then on return the scan location is set to the beginning of that string.")
    strippedString2 = [strippedString2 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\" "]];

    return [strippedString stringByAppendingString:strippedString2];
}

I will come back (much) later to clean it, and drill into the documentation of the class NSScanner to figure what I am missing, and had to take care with a manual string trimming.