2

What would be the best way to get every substring between double quotes and make it into an array?

For example, if the string (NSString) is:

@"abcd \"efgh\" ijklm \"no\" p \"qrst\" uvwx \"y\" z"

I want the result to be:

{@"efgh", @"no", @"qrst", @"y"}

as an NSArray.

ThomasW
  • 16,981
  • 4
  • 79
  • 106
Dennis
  • 3,506
  • 5
  • 34
  • 42
  • I guess the same question is asked plenty of time in different manner..!! Try to search first. – Yama May 21 '12 at 04:34
  • what is the reason behind having values within @"", you need string values? – rishi May 21 '12 at 04:34
  • I don't know if componentsSeparateByString: accepts escaped char's, but it's worth a shot. – CodaFi May 21 '12 at 04:37
  • It does accept them, why wouldn't it? –  May 21 '12 at 04:46
  • Try below post may be help full for your string split's in objective c http://stackoverflow.com/questions/6825834/objective-c-how-to-extract-part-of-a-string-e-g-start-with Welcome! – Dinesh May 21 '12 at 04:37

2 Answers2

6

This should get you started:

NSString *str = @"abcd \"efgh\" ijklm \"no\" p \"qrst\" uvwx \"y\" z";
NSMutableArray *target = [NSMutableArray array];
NSScanner *scanner = [NSScanner scannerWithString:str];
NSString *tmp;

while ([scanner isAtEnd] == NO)
{
    [scanner scanUpToString:@"\"" intoString:NULL];
    [scanner scanString:@"\"" intoString:NULL];
    [scanner scanUpToString:@"\"" intoString:&tmp];
    if ([scanner isAtEnd] == NO)
        [target addObject:tmp];
    [scanner scanString:@"\"" intoString:NULL];
}

for (NSString *item in target)
{
    NSLog(@"%@", item);
}
4

One way would be to use componentsSeparatedByString: to split them based on ". This should give you an array of words the count of which should be odd. Filter all the even numbered words into an array. This should be your desired array.

Alternatively look at NSPredicate.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105