Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split newline from NSString in ObjectiveC

For my new project. i have loaded my csv file content as a NSString. First, i need to split this by newline, then split each line by comma. How can i loop all this? Could you please help me?

CSV Content

"^GSPC",1403.36,"4/27/2012","4:32pm",+3.38,1400.19,1406.64,1397.31,574422720 "^IXIC",3069.20,"4/27/2012","5:30pm",+18.59,3060.34,3076.44,3043.30,0

ViewController.m

NSString* pathToFile = [[NSBundle mainBundle] pathForResource: @"quotes" ofType: @"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
if (!fileString) {
    NSLog(@"Error reading file.");
}

NSArray *array = [fileString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

for(int i=0; i<[array count]; i++){      
    //
}
like image 248
shebi Avatar asked Apr 29 '12 07:04

shebi


1 Answers

Might want to look into NSMutableArray.

// grab your file
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
for (int i = 0; i < [data count]; i++)
{
    [data replaceObjectAtIndex: i
                    withObject: [[data objectAtIndex: i] componentsSeparatedByString: @","]];
}

Relatedly, Dave DeLong has a proper library to address this need: https://github.com/davedelong/CHCSVParser

like image 132
Patrick Perini Avatar answered Nov 15 '22 16:11

Patrick Perini