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
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With