I have csv that comes with format:
a1, a2, a3, "a4,a5", a6
Only field with , will have quotes
Using Objective-C, how to easily parse this? I try to avoid using open source CSV parser as company policy. Thanks.
I have csv that comes with format:
a1, a2, a3, "a4,a5", a6
Only field with , will have quotes
Using Objective-C, how to easily parse this? I try to avoid using open source CSV parser as company policy. Thanks.
I agree with rmaddy that a full csv parsing algorithm is beyond the scope of SO, however, here is one possible way of tackling this:
NSString
NSString
, pushing each character back into another string.This is generally applicable to any language (using their respective native string classes) and such an algorithm can form a small basis for a full CSV parser. In this particular case however, you may not need any more functionality than this.
For some sample code, I would encourage you to have a look at my answer to this CSV-related question as it demonstrates a way of splitting and storing strings in Objective-C.
This snippet worked perfectly for me...
BOOL quotesOn = false;
NSString* line = @"a1, a2, a3, "a4,a5", a6";
NSMutableArray* lineParts = [[NSMutableArray alloc] init];
NSMutableString* linePart = [[NSMutableString alloc] init];
for (int i = 0; i < line.length; i++)
{
unichar current = [line characterAtIndex: i];
if (current == '"')
{
quotesOn = !quotesOn;
continue;
}
if (!quotesOn && current == ',')
{
if (linePart.length > 0)
[lineParts addObject: linePart];
linePart = [[NSMutableString alloc] init];
}
if (quotesOn || current != ',')
[linePart appendString: [line substringWithRange: NSMakeRange(i, 1)]];
}
if (linePart.length > 0)
[lineParts addObject: linePart];
My 5 elements are in the lineParts array...