Re: [newbie] Reading a CSV file
Re: [newbie] Reading a CSV file
- Subject: Re: [newbie] Reading a CSV file
- From: Dan Wood <email@hidden>
- Date: Sun, 02 Jun 2002 20:18:46 -0700
Here's some code that I am working on, to appear in a future
MacTech article. Feel free to make use of it (and comment on
it)!
@interface NSString ( tsv )
- (NSArray *) arrayFromTSV;
@end
@implementation NSString ( tsv )
/*" Build an array of dictionaries from a TSV (tab-separated
values) string. Blank lines and lines starting with "#" are
ignored. The first non-empty, non-comment line is assumed to be
the keys. Empty lines are not added to the array, so blank
lines (or lines with just tabs) are safely ignored. Missing
items aren't added to the dictionary. The string is assumed to
be separated with UNIX newlines only.
"*/
- (NSArray *) arrayFromTSV
{
NSMutableArray *result = [NSMutableArray array];
NSArray *lines = [self componentsSeparatedByString:@"\n"];
NSEnumerator*theEnum = [lines objectEnumerator];
NSArray *keys = nil;
int keyCount = 0;
NSString *theLine;
while (nil != (theLine = [theEnum nextObject]) )
{
if (![theLine isEqualToString:@""] && ![theLine
hasPrefix:@"#"]) // ignore empty lines and lines that start
with #
{
if (nil == keys) // Is keys not set yet? If so,
process first real line as list of keys
{
keys = [theLine componentsSeparatedByString:@"\t"];
keyCount = [keys count];
}
else // A data line
{
NSMutableDictionary *lineDict = [NSMutableDictionary dictionary];
NSArray *values = [theLine componentsSeparatedByString:@"\t"];
int valueCount = [values count];
int i;
for ( i = 0 ; i < keyCount && i < valueCount ; i++ )
{
NSString *value = [values objectAtIndex:i];
if (nil != value && ![value isEqualToString:@""])
{
[lineDict setObject:value forKey:[keys objectAtIndex:i]];
}
}
if ([lineDict count]) // only add the line if there was any data
{
[result addObject:lineDict];
}
}
}
}
return result;
}
@end
On Wednesday, May 29, 2002, at 12:52 am, Carl Gherardi wrote:
Hi all,
I'm trying to figure out how to open a text file and parse it
using Cocoa
(not unix calls).
Which classes should I be concentrating on?
Thanks
Carl Gherardi
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.
--
Dan Wood
Karelia Software, LLC
email@hidden
http://www.karelia.com/
Watson for Mac OS X:
http://www.karelia.com/watson/
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.