Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective c Split String Issue

I'm trying to split a string into an NSArray, however I'm having an issue ignoring strings that have speech marks in.

For example

NSString *example = @"100 200 300 \"TEST ITEM\" 500";
NSArray *array = [example componentsSeparatedByString:@" "];

However the array obviously gets created as 100, 100, 300, "Test, ITEM", 500. Is it possible to treat anything with " " as one?

Thanks

like image 497
Strikeforce Avatar asked May 12 '26 00:05

Strikeforce


1 Answers

You could use a well known CSV Parser which can be configured to use spaces as separators, and will treat double-quotes correctly. That assumes you want usual CSV-handling like escaping of double-quotes inside double-quoted strings, etc.

Otherwise, you'll probably need to write the parsing logic yourself; take a look at NSScanner, which would let you read up to a space or double-quote, look at what you get back, and then read to the next space/double-quote, etc.

Example:

@interface ItemParser : NSObject<CHCSVParserDelegate>

- (NSArray *)itemsFromString:(NSString *)input;

@end

@implementation ItemParser {
    NSMutableArray *_results;
}

- (NSArray *)itemsFromString:(NSString *)input {
    _results = [NSMutableArray array];

    NSStringEncoding encoding = [input fastestEncoding];
        NSInputStream *stream = [NSInputStream inputStreamWithData:[input dataUsingEncoding:encoding]];
    CHCSVParser *parser = [[CHCSVParser alloc] initWithInputStream:stream usedEncoding:&encoding delimiter:' '];
    parser.delegate = self;
    [parser parse];

    return _results;
}

- (void)parser:(CHCSVParser *)parser didReadField:(NSString *)field atIndex:(NSInteger)fieldIndex {
    [_results addObject:field];
}
@end

You'd use it like this:

NSString *example = @"100 200 300 \"TEST ITEM\" 500";
ItemParser *parser = [[ItemParser alloc] init];
NSLog(@"%@", [parser itemsFromString:example]);
like image 76
Jesse Rusak Avatar answered May 14 '26 14:05

Jesse Rusak